Changing UITableViewCell Selection Color in Storyboards with IBInspectable

Updated for Swift 3 on 12/18/16

Goal: Add the ability to change the selection color of a UITableViewCell in Storyboard

Recently I needed to change the cell selection color of a UITableViewCell. This can be done in a few lines of code using the "selectedBackgroundView" property on UITableViewCell. But since the ultimate goal is simply to change the selection color, it would be nice to have an attribute in storyboard so that we can set the selection color on any cell using the default Xcode color picker.

For this example I started with a simple tableView with four static cells. Each one will have a different selection color. All we need is a UITableViewCell subclass with one IBInspectable UIColor property.

class SelectableTableViewCell: UITableViewCell {

    @IBInspectable var selectionColor: UIColor = .gray {
        didSet {
            configureSelectedBackgroundView()
        }
    }

    func configureSelectedBackgroundView() {
        let view = UIView()
        view.backgroundColor = selectionColor
        selectedBackgroundView = view
    }

}

When you set a UITableViewCell to this subclass or another subclass that inherits from SelectableTableViewCell you will see a new "selectionColor" attribute in the Attributes Inspector. Also remember that you can set the alpha component of the color to achieve an effect similar to what Apple's default selection styles provide.

When the selectionColor is set in storyboard, the "didSet" property observer will be called at runtime. From there we just set the "selectedBackgroundView" property on the cell by creating an empty view and setting its background color to the new color.