I have a UITableView set up with a Core Data fetched results controller and custom cells created using a storyboard. Everything is working fine until I try conditionally setting the font color of a UILabel for some cells.
By default in the storyboard, each cell shows a “departure time” with a grey font. But, if the cell represents the user’s current location, the font should be blue. So I set up a conditional in configureCell (near the bottom of this snippet):
-(void) configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
if ([cell isMemberOfClass:[SectionDividerCell class]]) {
[self configureSectionDividerCell:(SectionDividerCell *)cell atIndexPath:indexPath];
}
else if ([cell isMemberOfClass:[VisitCell class]]) {
[self configureVisitCell:(VisitCell *)cell atIndexPath:indexPath];
}
}
-(void) configureVisitCell:(VisitCell *)cell atIndexPath:(NSIndexPath *)indexPath {
//Regular visit cell
Visit *visit = [self.fetchedResultsController objectAtIndexPath:indexPath];
//Set text content
cell.titlePlace.text = visit.place_name;
cell.arriveText.text = [visit getArrivalTimeDisplay:@"hh:mm a"];
cell.leaveText.text = [visit getDepartureTimeDisplay:@"hh:mm a"];
cell.durationText.text = visit.durationDisplay;
//Set fonts
[cell.durationText setFont:[UIFont fontWithName:@"Roboto-BoldCondensed" size:20.0]];
[cell.arriveText setFont:[UIFont fontWithName:@"Roboto-Light" size:12.0]];
[cell.titlePlace setFont:[UIFont fontWithName:@"Roboto-BoldCondensed" size:17.0]];
//If current location, make text blue
if (!visit.departure_time) {
[cell.leaveText setFont:[UIFont fontWithName:@"Roboto-Bold" size:12.0]];
[cell.leaveText setTextColor:[UIColor blueColor]];
}
else {
[cell.leaveText setFont:[UIFont fontWithName:@"Roboto-Light" size:12.0]];
}
//Get Image for cell
if (!cell.imgThumb.image) {
NSString *imageURL = [[docDir stringByAppendingString:@"/"] stringByAppendingString:visit.place.imageName];
[cell.imgThumb setImage:[[UIImage alloc] initWithContentsOfFile:imageURL]];
}
}
With the above code, the “Current Location” cell’s UILabel is correctly colored blue, but some other cells are also colored blue (seems to be random – happens to about 10% of the cells.
If I add this code within the else statement to set the color back to the default for cells that are not the current location, it fixes the problem:
[cell.leaveText setTextColor:[UIColor greyColor]];
But what I don’t understand is, why are some cells incorrectly having their font color set?
It’s not incorrect.
Yes, exactly. That’s because UITableView, for the sake of reducing memory footprint, re-uses table view cells. And when a cell is reused, UITableView doesn’t reset its properties, so You have to reset them to defaults. You can see this pattern in some code of mine, too, for example, this file browser UITableView shows symbolic links using light blue, but normal files in the default black color. Here you can also see the
elsebranch of the conditional statement.