按下按钮时获取 UITableView 单元格的行 [英] Getting row of UITableView cell on button press

查看:24
本文介绍了按下按钮时获取 UITableView 单元格的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个显示一行单元格的 tableview 控制器.每个单元格有 3 个按钮.我已将每个单元格的标签编号为 1、2、3.问题是我不知道如何找到按钮被按下的单元格.我目前只在按下其中一个按钮时获取发件人的标签.有没有办法在按下按钮时获取单元格行号?

I have a tableview controller that displays a row of cells. Each cell has 3 buttons. I have numbered the tags for each cell to be 1,2,3. The problem is I don't know how to find on which cell a button is being pressed. I'm currently only getting the sender's tag when one of the buttons has been pressed. Is there a way to get the cell row number as well when a button is pressed?

推荐答案

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

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.

这篇关于按下按钮时获取 UITableView 单元格的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆