Change cell appearance on selection

As an iOS developer you might have run into situations where you want to change the cell appearance when particular cell is selected.

Naive approach to this would be (Which by the way I did before I came to know about this little trick) to keep track of two indexPaths. (You can keep track of rows if tableView has only one section. In this case your default section for indexPath will be 0).

The reason you will need to keep reference to two indexPath is because when you select a row you can change the appearance. However, when another row is selected, you will have to change the appearance of newly selected row, but at the same time you have to reset the appearance of previously selected row. (Since that row is no longer selected). Besides, if you want to support multi-selection, things will get more complicated.

Fortunately, there is one easy solution

Create a UITableViewCell subclass for tableView cell and override following method.


- (void)setSelected:(BOOL)selected animated:(BOOL)animated

Make sure to call the


[super setSelected:selected animated:animated]; 

in the overridden method.

In the overridden method, check the value of selected flag to update the cell appearance. (e.g. changing text color, fonts or even the cell background color)

e.g. in the following example I am updating the background color of UILabel based on whether cell is selected or not.


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    if (selected) {
        self.cellTitleLabel.backgroundColor = [UIColor greenColor];
    } else {
        self.cellTitleLabel.backgroundColor = [UIColor whiteColor];
    }
}

To make things even simpler, I have created a demo of this example. You can find it as a subproject of my other iOS post. You can download it directly from GitHub project page.

Let me know if you have any other questions about this post. Happy coding and Happy New year