gpt4 book ai didi

ios - reloadData之后的indexPath.row错误

转载 作者:行者123 更新时间:2023-12-01 18:06:42 24 4
gpt4 key购买 nike

我正在尝试在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;
}

关于ios - reloadData之后的indexPath.row错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41293615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com