gpt4 book ai didi

iOS - UITableView 的选定单元格中的 UIButton

转载 作者:行者123 更新时间:2023-11-29 13:11:02 24 4
gpt4 key购买 nike

我正面临一个最重要的问题,这个问题几乎让我把电脑扔出窗外。我试图只在某些单元格上创建一个按钮,我对触发操作没有任何问题,但是当我向下滚动表格并返回到第一个单元格时,按钮是在其他单元格上创建的。换句话说,如果单元格 1 和 3 应该有按钮,当创建 tableview 时,它们是唯一有按钮的。当我再次向下和向上滚动时,单元格 2、3 和 4 也有按钮(没有特定规则)。该按钮也能正常工作,但它不应该在那里!

static NSString *CellIdentifier = @"Cell";
OpinionCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
cell= [[OpinionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

...一些有影响的代码......

if(([[aComment objectForKey:@"TypeMsg"] intValue]==310)&&([[parentMessage objectForKey:@"TypeMsg"] intValue]==310)){
UIButton *_openReplyButton = [[UIButton alloc] initWithFrame:CGRectMake(280, 5, 20, 20)];
[_openReplyButton setImage:[UIImage imageNamed:@"reply_button.png"] forState:UIControlStateNormal];
[_openReplyButton addTarget:self action:@selector(addRowsForShowReply:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:_openReplyButton];
NSLog(@"%@", [aComment objectForKey:@"Message"]);
}

非常感谢您的帮助!

最佳答案

这是 UITableView 的经典问题。我花了很长时间才弄清楚 TableView 所做的出队和重用过程。这是应该修复它的方法。

将初始化按钮的代码移到检查 cell == nil 的部分。这是因为您不应该向刚刚出列的单元格添加 subview ,因为您不知道该单元格是否已经添加了 subview 。此外,您应该为按钮设置一个标记或将其设为 OpinionCell 的属性。这样您以后就可以访问它。

然后,如果您确定该按钮应该可见,请设置 cell.replyButton.hidden = NO[cell viewWithTag:kMyButtonTag].hidden = NO非常重要,您应该将其设置为隐藏在else 子句中。否则,该按钮将显示在看似随机的单元格上。

希望这对您有所帮助!

关于iOS - UITableView 的选定单元格中的 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17373314/

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