简体   繁体   English

UITableViewCell中的UIButton的NSIndexPath

[英]NSIndexPath for UIButton in UITableViewCell

I'm trying to implement the block method outlined in the answer to the question in this link , but I don't understand how to set the block. 我正在尝试实现此链接问题答案中概述的block方法,但我不知道如何设置该block。 Assuming that... 假如说...

 cell.onButtonTapped = ^{
        [self buttonSelectedAtIndexPath:indexPath];
    }

is pseudo code, how would I actually implement this assuming I have a UITableViewCell (not a custom cell) and a UIButton within that cell. 是伪代码,假设我在该单元格中有一个UITableViewCell (不是自定义单元格)和一个UIButton ,我将如何实际实现呢? Is it possible to do this without creating my own UITableViewCell subclass? 是否可以在不创建自己的UITableViewCell子类的情况下执行此操作?

If you're gonna do it this way, you'd really have to make a UITableViewCell subclass which is a target of its button, has a property for the block and calls the block when the button is tapped. 如果要这样做,则实际上必须创建一个UITableViewCell子类,该子类是其按钮的目标,具有该块的属性,并在点击按钮时调用该块。

There's actually a simple way to know from which indexPath a subview (eg. the button here) of a cell is from. 实际上,有一种简单的方法可以知道单元格的子视图(例如此处的按钮)来自哪个indexPath。 First you'll need a point on the tableView's coordinates, which is contained by the subview. 首先,您需要在tableView的坐标上指定一个点,该点包含在子视图中。 Let's say you'll choose the center of the subview. 假设您要选择子视图的中心。 To convert it to the tableView's coordinates: 要将其转换为tableView的坐标:

CGPoint subViewCenter = [self.tableView convertPoint:subview.center fromView:subView.superView]; // because a view's center is on its superview's coordinates

to get the indexPath: 获取indexPath:

NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:subViewCenter];

No, as per the answer you are referring to, you need a custom UITableViewCell. 不,根据您所指的答案,您需要一个自定义UITableViewCell。 Essentially you are calling a method on the cell and passing the current indexPath for that cell. 本质上,您是在单元格上调用一个方法,并传递该单元格的当前indexPath。

Whether you use the block method or the delegate method you will need a custom UITableViewCell as you need somewhere to store the indexPath and a method to set it. 无论使用块方法还是委托方法,您都将需要自定义UITableViewCell,因为您需要在某个地方存储indexPath及其设置方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM