如何在自定义的tableViewCell中获取UIButton的indexPath?

Tzu*_*zit 4 iphone

我创建了一个tableViewCell,包括一个图像,两个文本标签和一个uibutton.该按钮被分配给一个动作方法(例如viewButtonPused:sender).

我习惯用tableView处理行选择:didSelectRowAtIndexPath:所以我可以判断选择了哪一行.但是使用uibutton及其动作方法......我怎么能说出来?

提前致谢.

Ale*_*pty 17

如果按钮的目标是UIViewController/ UITableViewController或维护对UITableView实例的引用的任何其他对象,这将很好地做到:

- (void)viewButtonPushed:(id)sender {
    UIButton *button = (UIButton *)sender;
    UITableViewCell *cell = button.superview; // adjust according to your UITableViewCell-subclass' view hierarchy
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    // use your NSIndexPath here
}
Run Code Online (Sandbox Code Playgroud)

使用这种方法可以避免额外的实例变量,并且在你有多个部分时可以正常工作.您需要有办法访问该UITableView实例.

编辑:正如有人在下面的评论中指出的那样,这种方法在iOS 7中爆发了.如果你仍然对使用这种方法而不是标签感兴趣,请务必UITableViewCell正确找到实例,即通过循环浏览超级视图直到找到它.

  • 这是一个非常糟糕的主意.经典的例子为什么,随着iOS 7 Apple更改了视图层次结构,现在这将无法正常工作. (2认同)