在我的应用程序中,我有一个 UITableView,它由多个自定义 UITableViewCells 组成。在我的 Storyboard中,我勾选了单选,因为我一次只想要一个选定的单元格。在我的 ViewController 中,我重写了 didSelectRowAtIndexPath
和 didDeselectRowAtIndexPath
,如下所示:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
TextsTableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
selectedCell.backgroundColor = [UIColor blueColor];
selectedCell.textLabel.textColor = [UIColor whiteColor];
self.chosenTextId = [NSNumber numberWithInteger:[selectedCell tag]];
self.chosenStaticText = [selectedCell.textLabel text];
NSLog(@"The textID: %@ and the text: %@", self.chosenTextId, self.chosenStaticText);
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath*)indexPath {
TextsTableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
selectedCell.backgroundColor = [UIColor whiteColor];
selectedCell.textLabel.textColor = [UIColor blackColor];
self.chosenTextId = nil;
self.chosenStaticText = nil;
}
只要我不滚动,一切似乎都工作正常(尽管我无法在不滚动的情况下进行检查)。我的日志仅包含我单击的正确选择的单元格。但是当我向下滚动时,也有其他单元格被选中。有谁知道可能会出现什么问题?
最佳答案
这里的问题是您的 UITableViewCell
正在被重用,这会保持它们的状态,因此只有在滚动时才会发生这种情况。您需要将选定的单元格 indexPaths 存储在存储集合对象中,例如 NSMutableArray
。然后在您的 cellForRowAtIndexPath
中,您可以检查是否应选择该单元格,如果是,请选择它,如果不是,请确保未选择它。
关于ios - 选择一个单元格错误地将其他几个单元格标记为 "selected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32909158/