在自定义 UITableViewCell 中按下 UIButton 时如何获取 indexPathForSelectedRow
Posted
技术标签:
【中文标题】在自定义 UITableViewCell 中按下 UIButton 时如何获取 indexPathForSelectedRow【英文标题】:How to get indexPathForSelectedRow when a UIButton is pressed inside a custom UITableViewCell 【发布时间】:2014-10-18 06:29:02 【问题描述】:我无法通过按下自定义 UITableViewCell 中的按钮来确定如何获取所选行的 indexPath。
我的 cellForRowAtIndexPath 中有:
self.rCell.reportUserButton.tag = indexPath.row;
在我的 prepareForSegue 中:
ReportUserViewController *reportUserVC = segue.destinationViewController;
reportUserVC.message = [self.receivedMessages objectAtIndex:self.rCell.reportUserButton.tag];
这是我的问题...self.rCell.reportUserButton.tag
设置为视图中最后一个单元格的值。
如果我想要第一个单元格,则始终设置最后一个单元格。
如何获取具有活动报告用户按钮的单元格的 indexPath????
【问题讨论】:
什么是self.rCell??为什么要保留对一个单元格的引用? 【参考方案1】:cellForRowAtIndexPath 在表格视图中创建和重用单元格时调用,您像下面的代码一样分配值意味着仅最后一次重用的单元格 indexPath 分配给您的单元格。
self.rCell.reportUserButton.tag = indexPath.row;
在单元格中使用委托传递值
// In CustomCell Class
@protocol yourdelegate <NSObject>
-(void)passCellIndexAction:(CustomCell *)cell;
@end
-(void)buttonClickAction
[delegate passCellIndexAction: self];
// In View controller class
-(void)passCellIndexAction:(CustomCell *)cell
ReportUserViewController *reportUserVC = segue.destinationViewController;
reportUserVC.message = [self.receivedMessages objectAtIndexcell.reportUserButton.tag];
【讨论】:
【参考方案2】:还有另一种方法:
- (NSIndexPath *)indexPathForRowAtPoint:(CGPoint)point
例如,如果使用自定义 详细信息 按钮和从该按钮到详细信息视图的 segue:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
if ([segue.identifier isEqualToString:@"news-detail"])
NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint: ((UIButton *)sender).superview.superview.center];
NSArray *keys = [self.dataSource allKeys];
NSDictionary *newsItem = [[self.dataSource objectForKey:[keys objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]; ;
[(MyDetail_ViewController *) segue.destinationViewController setDataItem:newsItem];
【讨论】:
indexPathForRowAtPoint 是要走的路,但是您对 superview.superview.center 的使用假定了视图层次结构的布局。您应该使用 convertPoint,如下所示: let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView)【参考方案3】:您应该在点击您的cell button
时使用delegate method
来告诉它有关tableViewController
的信息。
@protocol cellDelegate <NSObject>
-(void)calledOnButtonClick:(CustomCell *)cell;
@end
然后在您的单元格的按钮单击事件上调用委托,如
if ([delegate respondsToSelector:@selector(calledOnButtonClick:)])
[delegate calledOnButtonClick:self];
现在在你的 tableViewController
-(void)calledOnButtonClick:(CustomCell *)cell
NSIndexPath *iPath = [_tableView indexPathForCell:cell];
它会给你正确的索引路径
【讨论】:
以上是关于在自定义 UITableViewCell 中按下 UIButton 时如何获取 indexPathForSelectedRow的主要内容,如果未能解决你的问题,请参考以下文章
将项目添加到 .plist 并在自定义 UITableViewCell 中显示
如何在自定义 UITableViewCell 中更改 UIButton 标题的权重属性?
通过在另一个 ViewController 中按下按钮/在另一个 ViewController 中引用 UITableView 创建 UITableViewCell
UIButton 在自定义 UITableviewCell 中没有响应