我正在开发一个iOS应用程序,用户可以选择他们最喜欢的景点。我想用UITableView中的一个复选标记来显示这一点。调试时,我发现当用户选择(例如)4个景点并向下滚动时,其他景点也会有一个复选标记。即使用户还没有选择他们。这是一个常见的错误/故障吗?
代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = items[indexPath.row];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *tableCell = [tableView cellForRowAtIndexPath:indexPath];
BOOL isSelected = (tableCell.accessoryType == UITableViewCellAccessoryCheckmark);
if (isSelected) {
tableCell.accessoryType = UITableViewCellAccessoryNone;
}
else {
tableCell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}`
下面是一个.gif文件,向您展示在谣言中发生的事情:
发布于 2015-11-30 13:25:34
@property (nonatomic, strong) NSMutableSet *selectedIndexPaths;
- (void)viewDidLoad {
...
_selectedIndexPaths = [NSMutableSet set];
...
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
tableCell.accessoryType = ([self.selectedIndexPaths containsObject:indexPath])
? UITableViewCellAccessoryCheckmark
: UITableViewCellAccessoryNone;
...
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
UITableView *tableCell = [tableView cellForRowAtIndexPath:indexPath];
if ([self.selectedIndexPaths containsObject:indexPath]) {
[self.selectedIndexPaths removeObject:indexPath];
tableCell.accessoryType = UITableViewCellAccessoryNone;
} else {
[self.selectedIndexPaths addObject:indexPath];
tableCell.accessoryType = UITableViewCellAccessoryCheckmark;
}
...
}发布于 2015-11-30 13:15:34
这是一个非常常见的bug,但不是iOS错误。:)
问题是单元格被重用,如果您更改了单元格的一个方面,当它再次给您时,它不会自动重置为任何默认设置。
使用的策略是:将“选定”状态保存在用于填充单元格的数据中,然后在cellForRowAtIndexPath中打开或关闭附件。
发布于 2015-11-30 13:14:40
这不是窃听器/故障。应该是这样的。因为您正在使用dequeueReusableCellWithIdentifier。必须在cellForRowAtIndexPath中重置单元格的状态。
对于选定的单元格,应创建一个数组来处理所选单元格的索引。
https://stackoverflow.com/questions/33999456
复制相似问题