UITableViewCell可重用性问题。 修改一个单元格正在影响他人

每当select第3节的单元格时。 我正在更新DataSource数组,并且单元格的背景颜色因此正确地更改。

然而,每当我滚动回来,我开始看到具有修改背景颜色的随机单元格,知道我甚至没有在我的cellForRowAtIndexPath方法中提及它,并且我的tableView每个部分都从单独的数据源Array/Dictionary填充!

(我使用Storyboard来处理所有UI设置)

这是我的代码(关注第3节)

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ECTextFieldTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSettingsTextFieldCellReuseIdentifier forIndexPath:indexPath]; if (indexPath.section == 0) { cell.cellTextField.text = [self.personalInfoDataSource valueForKey:kUserValuesKey][indexPath.row]; } else if (indexPath.section == 1) { cell.cellTextField.text = [self.contactInfoDataSource valueForKey:kUserValuesKey][indexPath.row]; } else if (indexPath.section == 2) { cell.cellTextField.text = [self.professionalDetailsDataSource valueForKey:kUserValuesKey][indexPath.row]; } else if (indexPath.section == 3) { //---- Problems here UserMeta *metaObj = self.interestDataSource[indexPath.row]; cell.cellTextField.userInteractionEnabled = NO; cell.cellTextField.text = metaObj; if (self.user.INTEREST.count > 0 && [self.user.INTEREST contains:metaObj.name] ) { cell.backgroundColor = [UIColor redColor]; } } return cell; } 

在这里,我正在做所有的DataSource修改

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.section == 0 && indexPath.row == 2) { // Do Stuff } else if (indexPath.section == 3) { //---- Problems here ECTextFieldTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; cell.backgroundColor = [UIColor redColor]; UserMeta *metaObj = self.interestDataSource[indexPath.row]; [self.user.INTEREST addObject:metaObj]; } } 

正如你写的,单元格被重用。 在第3节中显示的单元格可以在第0节中重新使用。

因此,您必须确保所有参数都设置为已定义的状态。

这意味着,如果在第3节中将userInteractionEnabled设置为NO ,将背景颜色根据条件设置为红色,则必须将userInteractionEnabled设置为YES ,并将颜色设置为所有其他节中的默认颜色。 此外,如果条件为假,则必须在第3节中将颜色设置为默认颜色。

由于表格单元格在滚动时会被重用,因此无法对其初始状态进行任何假设。 在cellForRowAtIndexPath您需要在所有条件下设置背景颜色,而不是在一组有限的条件下。 例如,您可以在出现单元格后将背景颜色设置为白色,然后在if语句的一个分支中将其设置为红色。