且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按下按钮时获取 UITableView 单元格的行

更新时间:2023-12-03 20:22:58

你真的应该改用这个方法:

You should really be using this method instead:

CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];

Swift 版本:

let buttonPosition = sender.convert(CGPoint(), to:tableView)
let indexPath = tableView.indexPathForRow(at:buttonPosition)

这将根据按下的按钮的位置为您提供 indexPath.然后,如果您需要单元格或 indexPath.row 如果您需要行号,则只需调用 cellForRowAtIndexPath.

That will give you the indexPath based on the position of the button that was pressed. Then you'd just call cellForRowAtIndexPath if you need the cell or indexPath.row if you need the row number.

如果你是偏执狂,你可以在使用它之前检查 if (indexPath) ... 以防万一在那个点上找不到 indexPath表视图.

If you're paranoid, you can check for if (indexPath) ... before using it just in case the indexPath isn't found for that point on the table view.

如果 Apple 决定更改视图结构,所有其他答案都可能会失效.

All of the other answers are likely to break if Apple decides to change the view structure.