在iPhone的那个单元格中点击一个按钮,检测单元格行值?

War*_*ior 3 iphone cocoa-touch objective-c uitableview ios

我在单元格内容视图上创建了按钮.我想检测单击按钮的哪一行.

Jac*_*kin 5

你需要有你UIViewController通过创建从一个目标-动作接收事件UIButtonUIViewController,就像这样:

[button addTarget:self action:@selector(cellButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)

然后在你UIViewController的动作方法中,你可以利用UITableViews indexPathForCell:方法获得正确的NSIndexPath:

- (void) cellButtonClicked: (id) sender {
   UIButton *btn = (UIButton *) sender;
   UITableViewCell *cell = (UITableViewCell *) [[btn superview] superview];
   NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
   //do something with indexPath...
}
Run Code Online (Sandbox Code Playgroud)

  • 此方法在iOS 7中不再按预期工作,因为UITableViewCells中现在有更多视图.我定期使用此代码返回UITableViewCellScrollView而不是单元格. (2认同)