Can't change the backgroundColor of a UILabel in a Static Cell

Viewed 205

I have a table view with static cells. In there I have selected the Style Right Detail.

Now I would like to change the background colour of the Detail label on the right-hand side. Even though it's just a label, I'm not able to change the background colour in IB.

So I pulled it into a View Controller to do it programmatically.

@IBOutlet weak var ukPremiumLabel: UILabel!

override func viewDidLoad() {
        super.viewDidLoad()
        ukPremiumLabel.layer.backgroundColor = UIColor(red: 0/255, green: 159/255, blue: 184/255, alpha: 1.0).cgColor
}

I also tried it this way:

override func viewDidLoad() {
        super.viewDidLoad()
        ukPremiumLabel.backgroundColor = UIColor.blue
}

I'm not sure why it remains white.

enter image description here

2 Answers

You're using built-in UITableViewCell style, so backgroundColor of cell's detailTextLabel is somehow overridden after cell is created.

You can solve it by changing this color property after it's been already changed.

To do that, you can change this color inside overridden willDisplay method of your UITableViewController

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if cell.detailTextLabel == ukPremiumLabel {
        ukPremiumLabel.backgroundColor = .blue
    }
}

You can use IBDesignable/IBInspectable annotations for UILabel,

@IBDesignable
class BackgroundLabel: UILabel {
    @IBInspectable var persistentBackgroundColor: UIColor = UIColor.red {
        didSet {
            super.backgroundColor = persistentBackgroundColor
        }
    }

    override var backgroundColor: UIColor? {
        didSet {
            if backgroundColor != persistentBackgroundColor {
                backgroundColor = persistentBackgroundColor
            }
        }
    }
}

And in UITableViewCell assign the BackgroundLabel for the detailTextLabel,

Image

Related