Reputation: 21
I want the first item of my tableView to be a different color than the rest of the list.
so I:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.text = [_content objectAtIndex:indexPath.row];
if (indexPath.row==0){
cell.textLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0.6 alpha:1];
}
return cell;
}
and had an odd phenomenon happen. 10 items later in the list, that item too changed color. Thought it might be "0" recurring. So I tried:
if ([cell.textLabel.text isEqualToString:@"Title of my first item"]){ cell.textLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0.6 alpha:1]; }
well, 10 items later, still changing that item's color. Any ideas?
Upvotes: 2
Views: 40
Reputation: 900
UITableView's do not allocate a new cell for every row. Instead, to save on memory, you call dequeueReusableCellWithIdentifier:, which grabs a cell that has previously been allocated. What I suspect is happening is that your screen can hold 10 cells, and so when your first cell scrolls off screen, it gets reused for cell 11, but its text color remains the same. To fix this, simply add an else statement to your color assignment.
if (indexPath.row==0){
cell.textLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0.6 alpha:1];
}
else {
cell.textLabel.textColor = [UIColor someOtherColor];
}
That way, when the first cell gets reused, its color will be reset.
Upvotes: 3