UITableViewCell可重用性问题。修改一个单元格会影响其他单元格

时间:2016-08-29 04:22:46

标签: ios xcode uitableview reuseidentifier

每当选择第3节中的单元格时。我正在更新DataSource数组,因此单元格的背景颜色正在发生变化。

然而,每当我向上滚动时,我都会看到具有修改背景颜色的随机单元格,知道我甚至不会在我的cellForRowAtIndexPath方法和tableView中的每个部分中提及它是从单独的DataSource 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];

} 

}

2 个答案:

答案 0 :(得分:3)

正如您所写,细胞被重复使用。第3节中显示的单元格可以在第0部分重复使用。

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

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

答案 1 :(得分:1)

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