ios - 自定义 UITableViewCell 快速滚动的奇怪行为

标签 ios uitableview

我有一个包含 5 个部分的分组 tableView。 tableView 使用自定义 UITableViewCell,其中有 2 个标签和 4 个按钮。当我在表格开头选择 1 个或多个按钮,然后滚动到表格末尾时,我发现这些按钮在最后一个单元格中选择,有时在倒数第二个单元格中。在我看来,dequeueReusableCellWithIdentifier存在一些问题,但我无法弄清楚。 为了清楚起见,我在 viewDidLoad 中有这段代码:

// table cell
UINib *nib = [UINib nibWithNibName:@"SMRateMeetingTableViewCell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:@"SMRateMeetingTableViewCell"];

这在我的 cellForRowAtIndexPath 中:

SMRateMeetingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SMRateMeetingTableViewCell" forIndexPath:indexPath];
// Configure the cell...
if (cell == nil) {
    cell = [[SMRateMeetingTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SMRateMeetingTableViewCell"];
}

非常基本的东西。 我添加了一些屏幕以便更好地理解。 enter image description here

enter image description here

enter image description here

编辑:添加按钮代码。 为了更容易分析,我们假设自定义单元格中只有 1 个按钮 这是 TableView 代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SMRateMeetingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SMRateMeetingTableViewCell" forIndexPath:indexPath];
// Configure the cell...
if (cell == nil) {
    cell = [[SMRateMeetingTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SMRateMeetingTableViewCell"];
}
//the tag will allow me to understand in which section is the button
cell.firstYesButton.tag = indexPath.section;

[cell.firstYesButton addTarget:self action:@selector(firstYesButtonAction:) forControlEvents:UIControlEventTouchUpInside];

return cell;
}

以及与按钮关联的相关方法:

-(IBAction)firstYesButtonAction:(id)sender
{
UIButton *senderButton = (UIButton *)sender;
[self.votesArray replaceObjectAtIndex:(senderButton.tag*2) withObject:[NSNumber numberWithInt:1]];
//NSLog(@"%@", self.votesArray );
}

这是自定义单元的实现文件中的代码:

@implementation SMRateMeetingTableViewCell

- (void)awakeFromNib {
// Initialization code
[self.firstYesButton setImage:[UIImage imageNamed:@"yesRateDisable.png"]   forState:UIControlStateNormal];
}

- (IBAction)firstYesAction:(id)sender {
[self.firstYesButton setImage:[UIImage imageNamed:@"yesRateEnable.png"] forState:UIControlStateNormal];
}

最佳答案

这是因为 TableView 正在回收您的单元格。这就是 dequeueReusableCellWithIdentifier: 方法所做的。因为它是回收 View 而不是总是创建新 View ,所以您将必须设置某些属性,例如按钮的选定状态,否则它们将保留它们入队时的属性。

关于ios - 自定义 UITableViewCell 快速滚动的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26504739/

相关文章:

ios - 如何使用 URL Swift 3 下载图像?

iOS: [self.view setNeedsDisplay];

ios - UITableView 在重新加载数据后不会立即显示单元格

ios - uiTableViewCell 添加行和图像,第二次点击删除行

ios FBDialogs presentShareDialogWithLink 回调返回错误

ios - 将 int 和 int 设置为 0 会节省内存吗?

iphone - 为什么我的 UITableView 无法识别 UITableViewCell 中的 Touch?

ios - 如何阻止 UITableView 在弹出后返回顶部单元格

ios - Swift:为 UITableViewController 子类使用变量

iphone - 如何切换方向变化的 View