在UITableViewCell中添加和删除UIButton的目标操作的最佳方法是什么。
对于每一行,我将根据行索引进行不同的按钮操作。显示请告诉我在哪里添加按钮的添加目标并删除按钮的目标。
我在询问要使用的代理和数据源。
答案 0 :(得分:1)
in
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[cell.btn1 removeTarget:self action:@selector(action1:) forControlEvents:UIControlEventTouchUpInside];
[cell.btn1 removeTarget:self action:@selector(action2:) forControlEvents:UIControlEventTouchUpInside];
cell.btn1.tag = indexPath.row;
if(indexPath.row%2)
{
[cell.btn1 addTarget:self action:@selector(onbtnWeighIn:) forControlEvents:UIControlEventTouchUpInside];
}
else{
[cell.btn1 addTarget:self action:@selector(onBtnViewTable:) forControlEvents:UIControlEventTouchUpInside];
}
}
答案 1 :(得分:1)
从按钮
中删除所有操作 [button removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];
为按钮添加操作
[button addTarget:self action:@selector(action1Method) forControlEvents:UIControlEventTouchUpInside];
请注意,如果由于状态更改而将按钮从一个操作切换到另一个操作,则最好删除操作。否则,即使您为表重新加载数据,所有操作也都会显示出来。
答案 2 :(得分:0)
将tag
值设置为button
中的每个TableViewCell
并添加target
,如下所示。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
cell.btn.tag = indexPath.row;
[btn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
现在添加一个选择器方法btnTapped
,如下所示。此方法每次调用tableview单元格中的每个按钮单击事件。
- (void)btnTapped:(UIButton *)sender {
UITableViewCell * cell = [[sender superview] superview];
NSIndexPath * path = [self.tableView indexPathForCell:cell];
}
这里有indexpath
所选按钮,可根据需要自定义。