我正在尝试在tableView行中单击按钮的indexPath.row
。
当用户单击此按钮时,我会很好地得到与该按钮对应的index.row
,但是当我通过调用reloadData
将更多对象添加到源数组以创建更多单元格时,每个单元格中的rowButtonClicked
不再为我提供正确的indexPath.row
示例我按索引20,现在打印的indexPath.row
是9。
在cellForRowAtIndexPath
中将事件添加到按钮:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
lBtnWithAction = [[UIButton alloc] initWithFrame:CGRectMake(liLight1Xcord + 23, 10, liLight1Width + 5, liLight1Height + 25)];
lBtnWithAction.tag = ROW_BUTTON_ACTION;
lBtnWithAction.titleLabel.font = luiFontCheckmark;
lBtnWithAction.tintColor = [UIColor blackColor];
lBtnWithAction.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
[cell.contentView addSubview:lBtnWithAction];
}
else
{
lBtnWithAction = (UIButton *)[cell.contentView viewWithTag:ROW_BUTTON_ACTION];
}
//Set the tag
lBtnWithAction.tag = indexPath.row;
//Add the click event to the button inside a row
[lBtnWithAction addTarget:self action:@selector(rowButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
要对单击的索引进行操作:
-(void)rowButtonClicked:(UIButton*)sender
{
//Get the index of the clicked button
NSLog(@"%li", (long)sender.tag);
[self doSomething:(long)sender.tag];
}
常数h
#define ROW_BUTTON_ACTION 9
更改tableView的初始项时,为什么给出错误的索引?有办法解决这个问题吗?
最佳答案
看来您正在弄乱按钮标签。设置标签后
lBtnWithAction.tag = indexPath.row;
您将无法正确获得按钮
lBtnWithAction = (UIButton *)[cell.contentView viewWithTag:ROW_BUTTON_ACTION];
(假设
ROW_BUTTON_ACTION
是一个常量)。 lBtnWithAction
始终都是nil
,除非indexPath.row
等于ROW_BUTTON_ACTION
。我建议将
UITableViewCell
子类化,在其中添加一个按钮属性,然后直接引用它而不是通过标签进行搜索。在这种情况下,您将可以自由地为按钮使用标签:) –@interface UIMyTableViewCell : UITableViewCell
@property (nonatomic, strong, nonnull) UIButton *lBtnWithAction;
@end
然后在
cellForRowAtIndexPath
中:- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIMyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UIMyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell.lBtnWithAction addTarget:self action:@selector(rowButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
cell.lBtnWithAction.tag = indexPath.row;
return cell;
}