我有一个包含 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"];
}
非常基本的东西。 我添加了一些屏幕以便更好地理解。
编辑:添加按钮代码。 为了更容易分析,我们假设自定义单元格中只有 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/