There is an annoying mistake that I cannot fix.
I have a CustomCell , and in it I have a subview that changes color depending on the value of the object.
- (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; }
Everything works fine, except when I delete the row with redColor = YES from the table view and I scan to show rows that were not visible. The first row that becomes visible (the first row that reuses a reused cell) is red, although this row is redColor = NO . And if I scroll again and hide the cell and then show it again, the color will be set to clearColor, as it should be.
I think this is due to the fact that it reuses the cell just removed. Therefore, before reusing, I try to use the contents of reset. In CustomCell.m
- (void)prepareForReuse { [super prepareForReuse]; self.clearsContextBeforeDrawing = YES; self.contentView.clearsContextBeforeDrawing = YES; self.colorView.backgroundColor = [UIColor clearColor]; }
But that does not work. Apple Doc says
Divide the table delegate in tableView: cellForRowAtIndexPath: should always reset all content when reusing a cell.
What is the correct way to keep reset? Do I need to remove subviews from the supervisor?
Thank you in advance
source share