Reputation: 297
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
Upvotes: 1
Views: 15896
Reputation: 11
In the cell itself in the method setSelected you can override it and then provide whatever colour or highlighted state you want:
override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated)
if isSelected {
// your color or highlited here
} else {
// your colour or highlighted here
}
}
Upvotes: 1
Reputation: 1
In cellForRowAt
indexPath
you can just add this line
cell.textLabel?.textColor = UIColor.blackColor()
Upvotes: 0
Reputation: 131
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 @IBOutlet
s. 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)
Upvotes: 8
Reputation: 1639
if you (use/not use) a custom cell(as xib), you can select the lable, and from utilities, go to highlighted and change the color to the color you want to show in selection.
and this is a snapshot to be more clear :)
Upvotes: 7
Reputation: 24572
You can set the color in didSelectAtIndexPath
and didDeselectAtIndexPath
and cellForRowAtIndexPath
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.textColor = UIColor.blackColor()
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.textColor = UIColor.redColor()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Dequeue cell
cell.textLabel?.textColor = UIColor.redColor()
}
Upvotes: 5