Swift Change textColor on Selection

user3581203 picture user3581203 · Jan 14, 2015 · Viewed 14.4k times · Source

How do I change the textColor of a label or a cell on selection in iOS Swift?

I want the background to not to change. Only textColor and seperatorColor if any. Something like:

label.highlightedTextColor = UIColor.whiteColor();

I have seen this happen in some apps that the color changes. But I cannot get any near to it. According to Apple Dev Reference:

Subclasses that use labels to implement a type of text button can use the value in this property when drawing the pressed state for the button. This color is applied to the label automatically whenever the highlighted property is set to true.

But, labels compile fine and don't change color on highlight. Buttons do not have highlightedTextColor

Answer

Mario Subotic picture Mario Subotic · Mar 8, 2016

I've tried setting it in didSelectAtIndexPath and didDeselectAtIndexPath but the color was getting changed with a delay. I didn't like that.

This is how I ended up solving the problem:

I have subclassed my UITableViewCell and connected all the @IBOutlets. In awakeFromNib() I simply did this:

@IBOutlet weak var myLabel: UILabel!


override func awakeFromNib() {
    super.awakeFromNib()        

    self.myLabel.highlightedTextColor = .blackColor()

}

Works perfectly now!

btw this is my first ever answer on stack overflow please be nice to me 😊 hehe

(I'm using Swift 2.0 and Xcode 7.2.1)