UITableViewCell selected row's text color change

Maulik picture Maulik · Apr 30, 2011 · Viewed 49.4k times · Source

I am having a tableview and I want to know that how can I change the selected row's text color, say to Red ? I tried by this code :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell= [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];

    cell.text = [localArray objectAtIndex:indexPath.row];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    cityName = [localArray objectAtIndex:indexPath.row];

    UITableViewCell* theCell = [tableView cellForRowAtIndexPath:indexPath];
    theCell.textColor = [UIColor redColor];
    //theCell.textLabel.textColor = [UIColor redColor];

    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

(1) When I select any row then text color changed to the red but when I select another then previously selected row's text remains red. how can I solve this ?

(2) When I scroll the table text color change to the black color how to solve this ?

Thanks..

Answer

Ole Begemann picture Ole Begemann · Apr 30, 2011

Do this in tableView:cellForRowAtIndexPath::

cell.textLabel.highlightedTextColor = [UIColor redColor];

(And don't use cell.text = ... anymore. It has been deprecated for almost 2 years now. Use cell.textLabel.text = ... instead.)


As Raphael Oliveira mentioned in the comments, if the selectionStyle of your cell equals UITableViewCellSelectionStyleNone this won't work. Check Storyboard as well for the selection style.