如何在tableView中findtapPath的附件button

我有一个简单的UITableView和几行。 当用户点击单元格附件button时(与detailsSegue连接),我想知道单元格是哪一行,所以我可以从我的数组中select正确的对象,并将它分配给下一个视图的variables。

我已经使用委托方法tableview:accessoryButtonTappedForRowWithIndexPath:和分配indexPath值到我的私有财产myRow 。 比在prepareForSegue:sender:方法我用我self.myRow.row值从数组中select正确的对象。

我的问题是,这两个方法似乎执行错误的顺序。 从NSLog中我可以看到prepareForSegue:sender:方法首先被执行,而我的委托方法正在改变self.myRow值。

所以prepareForSegue:sender:方法总是把错误的对象传递给下一个视图(之前被点击过的视图)。

对不起,我的英文家伙。 提前感谢您的帮助。

 -(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { self.myRow = indexPath; NSLog(@"tapped button at row: %i",self.myRow.row); } -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if([segue.identifier isEqualToString:@"addSegue"]) { AddViewController *avc = segue.destinationViewController; avc.delegate = self; } else if ([segue.identifier isEqualToString:@"detailsSegue"]) { NSLog(@"Segue row: %i",self.myRow.row); Annotation *annotation = [self.viewsList objectAtIndex:self.myRow.row]; NSLog(@"Segue annotation object: %@",annotation.title); DetailsViewController *dvc = segue.destinationViewController; dvc.wikiKey = annotation.title; } } 

正如你已经发现的,系统发送tableview:accessoryButtonTappedForRowWithIndexPath:消息之前向你prepareForSegue:sender: tableview:accessoryButtonTappedForRowWithIndexPath:消息。

但是 ,当它向您发送prepareForSegue:sender:消息时, sender参数是包含附件视图的UITableViewCell 。 您可以使用它来确定哪个行的附件button被点击:

 else if ([segue.identifier isEqualToString:@"detailsSegue"]) { NSIndexPath *indexPath = [self.tableView indexPathForCell:sender]; Annotation *annotation = [self.viewsList objectAtIndex:indexPath.row]; DetailsViewController *dvc = segue.destinationViewController; dvc.wikiKey = annotation.title; } 

发件人将是附件button,对不对? 在这种情况下,您应该能够通过超级视图查找其包含的单元格,然后获取该单元格的索引path。 我之前使用过这样的方法来完成第一部分:

 + (UITableViewCell *)findParentCellOfView:(UIView *)view { if (view == nil || [view isKindOfClass:[UITableViewCell class]]) { return (UITableViewCell *)view; } return [self findParentCellOfView:[view superview]]; } 

//我告诉你一个简单,更好,更简单的select:

//解决方法: – 您可以在tableView的这个方法中为附件视图的button分配标签

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // set accessory view UIButton *oValidHomeAccessryBtn = [UIButton buttonWithType:UIButtonTypeCustom]; // set target of accessory view button [oValidHomeAccessryBtn addTarget:self action:@selector(AccessoryAction:) forControlEvents:UIControlEventTouchUpInside]; // set tag of accessory view button to the row of table oValidHomeAccessryBtn.tag =indexPath.row; // set button to accessory view cell.accessoryView = oValidHomeAccessryBtn ; } 

//使你在select器中传递的方法获得标签值,并且你会得到点击辅助视图的indexPath

 - (void)AccessoryAction:(id)sender { NSLog(@"%d",[sender tag]); } 

这是获得您点击附件视图的行的indexPat最简单的方法。

你需要做的是从segue方法中以编程方式调用segue 。 假设您使用的是故事板,则需要取消故事板中的segue和委托方法的使用:

 [self performSegueWithIdentifier: @"IdentifierNameHere" sender: self];