有一个烦人的错误,我无法解决.
我有一个CustomCell,在其中我有一个子视图,根据对象的值改变它的颜色.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"CustomCell"; CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; if (cell == nil) { cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } MyObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath]; if ([object.redColor isEqualToNumber:[NSNumber numberWithBool:YES]]) { cell.colorView.backgroundColor = [UIColor redColor]; } else { cell.colorView.backgroundColor = [UIColor clearColor]; } return cell; }
这一切都正常,除非我从tableview中删除了一行redColor = YES,并滚动显示不可见的行.变为可见的第一行(重用可重用单元格的第一行)具有红色,即使该行为redColor = NO.如果我再次滚动并隐藏单元格然后再次显示它,颜色将设置为clearColor,它应该是这样的.
我认为这是因为它重用了刚被删除的单元格.
所以我在重用之前尝试重置单元格的内容.
在CustomCell.m中
- (void)prepareForReuse { [super prepareForReuse]; self.clearsContextBeforeDrawing = YES; self.contentView.clearsContextBeforeDrawing = YES; self.colorView.backgroundColor = [UIColor clearColor]; }
但这不起作用.
Apple Doc说
The table view’s delegate in tableView:cellForRowAtIndexPath: should always reset all content when reusing a cell.
提前致谢
解决方法
这似乎有效.
我在CustomCell.m中的prepareForReuse时删除了单元格的contentView
- (void)prepareForReuse { [super prepareForReuse]; // Clear contentView BOOL hasContentView = [self.subviews containsObject:self.contentView]; if (hasContentView) { [self.contentView removeFromSuperview]; } }
在cellForRowAtIndexPath中再次添加它
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Cell static NSString *cellIdentifier = @"CustomCell"; CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; if (cell == nil) { cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } // Restore contentView BOOL hasContentView = [cell.subviews containsObject:cell.contentView]; if (!hasContentView) { [cell addSubview:cell.contentView]; } // Configure cell MyObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath]; if ([object.redColor isEqualToNumber:[NSNumber numberWithBool:YES]]) { cell.colorView.backgroundColor = [UIColor redColor]; } else { cell.colorView.backgroundColor = [UIColor clearColor]; } return cell; }
希望这会对某人有所帮助.