我在UITableViewCell中添加了一个UIButton,在该按钮的操作中,我添加了以下代码来获取单元格的indexPath。但它不断返回错误 - 'NSInvalidArgumentException',原因:' - [UITableViewCell indexPathForCell:]:无法识别的选择器发送到实例0x7cea3fc0'
有人可以告诉我该怎么做吗?
- (IBAction)navigateMap:(id)sender {
__strong UIButton *button=(UIButton *) sender;
UITableViewCell *cell = (UITableViewCell *)button.superview;
UITableView *tableView = (UITableView *)cell.superview;
NSIndexPath *indexPath = [tableView indexPathForCell:cell];
//rest of the logic
}
完整代码
- (IBAction)navigateMap:(id)sender {
__strong UIButton *button=(UIButton *) sender;
UITableViewCell *cell = (UITableViewCell *)button.superview;
UITableView *tableView = (UITableView *)cell.superview;
NSIndexPath *indexPath = [tableView indexPathForCell:cell];
CombinedStations *inButton=[[CombinedStations alloc] init];
inButton=[_finalStationList objectAtIndex:indexPath.section];
_universalRegion->center.latitude=inButton.latitude;
_universalRegion->center.longitude=inButton.longitude;
NSString *launchUrl=@"";
launchUrl= [launchUrl stringByAppendingString:@"http://maps.google.com/maps?daddr="];
NSString *tmpLat = [[NSString alloc] initWithFormat:@"%f", _universalRegion->center.latitude];
NSString *tmpLong = [[NSString alloc] initWithFormat:@"%f", _universalRegion->center.longitude];
NSString *llat=[tmpLat stringByAppendingString:[@"," stringByAppendingString:tmpLong]];
launchUrl=[@"http://maps.google.com/maps?daddr=" stringByAppendingString:llat];
launchUrl=[launchUrl stringByAppendingString:[@"&saddr=" stringByAppendingString:@"Current Location"]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[launchUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
答案 0 :(得分:1)
button
的超级视图是单元格的contentView
。尝试获取按钮的超级视图的超级视图:
UITableViewCell *cell = button.superview.superview;
恕我直言,这是一个非常糟糕的设计。
答案 1 :(得分:1)
试试这个,这个很容易获得表的索引路径。
- (IBAction)navigateMap:(id)sender {
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:tableViewName];
NSIndexPath *indexPath = [tableViewName indexPathForRowAtPoint:buttonPosition];
}
答案 2 :(得分:0)
尝试从tableView获取indexpath。只需为该单元创建一个委托,并在点击按钮时触发它。
符合tableView所有者内的委托。无论何时捕获回调,都要向tableview询问委托中传入单元格的indexPath。
- (void)cell:(SampleCell *)cell actionButtonTapped:(UIButton *)button
{
self.currentIndexPath = [self.tableView indexPathForCell:cell];
}