iOS滚动UITableView时展开/select的自定义UITableViewCells状态更改

我有我的tableview中的自定义单元格的列表,当我滚动一切似乎罚款和单元格似乎是在相同的顺序。 我有我的单元格的一些function – 当我select一个单元格(并dynamic扩展)背景颜色的变化和一些其他自定义单元格属性。 一旦我这样做,然后我开始滚动,不同的单元格,我甚至没有触及之前显示,select(扩大),单元格只有当我手动select到正确的数据更新。 我似乎看到重复和各种疯狂。

我知道这里有很多关于这个的post,但是对于我来说,到目前为止还没有任何工作。 想就我能做些什么来阻止这种荒谬的行为的一些投入。

我已经发布了一些代码,让你更好地了解我在做什么。 我知道'dequeueReusableCellWithIdentifier'是罪魁祸首,但不知道替代。

作为旁注,这是一个tableview(它自己的xib),它是一个大视图的子视图(也是一个xib)。 我也已经注册了桌面视图的笔尖。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:myIndentifier forIndexPath:indexPath]; if(self.currentSelectedIndex){ if(self.previousSelectedIndex){ //collapse cell //configure cell in method(change background color etc) } else{ //expand cell //configure cell in method(change background color etc) } } } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { self.currentSelectedIndex = indexPath; [tableView beginUpdates]; if(self.currentSelectedIndex){ if(self.previousSelectedIndex && (self.previousSelectedIndex != self.currentSelectedIndex)){ [tableView reloadRowsAtIndexPaths:@[self.currentSelectedIndex, self.previousSelectedIndex] withRowAnimation:UITableViewRowAnimationAutomatic]; } else{ [tableView reloadRowsAtIndexPaths:@[self.currentSelectedIndex] withRowAnimation:UITableViewRowAnimationAutomatic]; } } [tableView endUpdates]; if(self.previousSelectedIndex == self.currentSelectedIndex){ self.previousSelectedIndex = nil; } else{ self.previousSelectedIndex = self.currentSelectedIndex; } } 

我该怎么做,或者如何确保列表中没有任何东西“似乎”被选中(展开),或者当我滚动时看起来不会看到重复的东西? 我已经跟踪了我当前和最后select的索引(如代码所示),所以我想我可以用它来做什么?

离去的单元格被重用

知道单元格被重用,所以UITableViewCell的外观在该单元格的整个生命周期中都是持久的。

这意味着如果你没有显式地reset你的单元格的所有表示视图,并且只是在cellForRowAtIndexPath中将其返回,你所返回的可能是一个当前选定(或取消select)的caching单元格。

prepareForReuse可能重置表格单元格的位置。


devise说明:
你如何维护self.currentSelectedIndexself.previousSelectedIndex ? 这通常是相当危险的,因为你正试图复制UITableView行为。 这是例如,不太可能与多个select。 例如,设置一个主动select不太可能处理操作系统didDeselectRowAtIndexPath ,例如键盘解除的结果。