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
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)
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()
}
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 :)
在cellForRowAt
indexPath
您只需添加此行即可
cell.textLabel?.textColor = UIColor.blackColor()
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.