Custom Selected view for UITableViewCell

How to make custom selected background view for UITableViewCell.

Recently I came across interesting problem where we were supposed to show multiple choice question format in UITableView. When user selected a cell, the bullet image for that cell would get toggled on/off based on select/deselect action. However, what I needed was cell background should remain unchanged in this process.

Obviously I could do something like this,

tableView.allowsSelection = false,

but unfortunately I also needed to keep track if that cell was indeed selected or not and then toggle adjacent bullet image.

To give more clear idea, view would look like this without any selected option.

And this is how it should look when user selects an option. (Notice how cell background hasn't got changed, but bullet state has. Based on toggle state.)

Each option is modeled as a tableViewCell with dynamic height. (Thanks to iOS8!)

I overrode UITableViewCell to decide if cell had been selected or deselected as follows :


override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    if(selected) {
        selectionIndicator.image = UIImage(named: "button_on")
    } else {
        selectionIndicator.image = UIImage(named: "button_off")
    }
}

That was easy, but it didn't get rid of cell background color when it was selected. So I had to chip in another trick to fix this issue.

Changing selected background view for cell

What I did was simply replacing selectedBackgroundView which is basically The view used as the background when cell is selected.


var whiteBackgroundView = UIView(frame:self.frame)
whiteBackgroundView.backgroundColor = UIColor.whiteColor() 
self.selectedBackgroundView = whiteBackgroundView

Since I wanted UIColor to remain white I have chosen this value, but you can customize it with any value you want.