0
votes

I am facing a strange issue. I have a tableview controller in Storyboard with 5 prototype cells. Each cell has one label and one image. I am trying to change text color of the labels and images when cell selected programmatically like as follow.

In cellForRowAtIndexPath method
{
     // Using tags I am getting labels from storyboard.

    label1 = (UILabel *)[cell.contentView viewWithTag:101];
    label2= (UILabel *)[cell.contentView viewWithTag:102];
    label3 = (UILabel *)[cell.contentView viewWithTag:103];
    label4 = (UILabel *)[cell.contentView viewWithTag:104];
    label5 = (UILabel *)[cell.contentView viewWithTag:105];


    label1.textColor =[UIColor blackColor];
    label2.textColor =[UIColor blackColor];
    label3.textColor =[UIColor blackColor];
    label4.textColor =[UIColor blackColor];
    label5.textColor =[UIColor blackColor];
}

In didSelectRowAtIndexPath method

{

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

label1 = (UILabel *)[cell.contentView viewWithTag:101];
label2 = (UILabel *)[cell.contentView viewWithTag:102];
label3 = (UILabel *)[cell.contentView viewWithTag:103];
label4 = (UILabel *)[cell.contentView viewWithTag:104];
label5 = (UILabel *)[cell.contentView viewWithTag:105];

Here I want to change selected label text color to white when selected otherwise it should be black. I am able to change text color to white when selected but I am not able to set text color back to black if I select other cell.

2

2 Answers

2
votes

In didDeselectRowAtIndexPath you can change the colour back to black.

Use UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; To get the cell.

1
votes

Why don't you create UITableViewCell subclass and override setSelected:animated: and setHighlighted:animated:. There you can update colors of your labels and change images easily. In example like this:

 - (void)setSelected:(BOOl)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    _label.textColor = (selected ? _selectedColor : _unselectedColor);

}

You can change your cell subclass usign Identity inspector. Changing class using Identity inspector