[英]When the button in TableView cell pressed, how do I know the button of which row of cell pressed?
我有一个自定义的TableView单元格,其中有一个按钮。 表格视图中有许多行使用了相同的自定义单元格。 现在,如果按下其中一个单元格的按钮。 我想知道按钮在哪一行单元格中?
(1)。 在此方法cellForRowAtIndexPath:
,为按钮分配一个tag
。 例如:
cell.yourbutton.tag = indexPath.row;
(2)。 使用相同的选择器为您的按钮添加操作
[cell.yourbutton addTarget:self action:@selector(cellButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
(3)。 然后
-(void)cellButtonClicked:(UIButton*)sender
{
NSIndexPath *path = [NSIndexPath indexPathForRow:sender.tag inSection:0];
}
您可以定义自定义属性,并可以如下使用它:-
#define kCustomProperty @"CustomProperty"
将您的对象与该自定义属性相关联,如下所示
objc_setAssociatedObject(yourButton,kCustomProperty , yourCellIndexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
使用与下面相同的属性和对象获取数据
NSIndexPath *yourCellIndexPath = (NSIndexPath *)objc_getAssociatedObject(yourButton, kCustomProperty);
如果您不想使用标签,则可以通过编码创建一种自定义属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.