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

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

问题描述

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

解决方案

你应该真正使用这种方法相反:

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

Swift版本:

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

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

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



所有其他答案都可能是如果Apple决定更改视图结构,则会中断。


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 version:

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

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 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.

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

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

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