I have a UIlabel on a UITableViewCell, which I've created programmatically (i.e. not a nib or a subclass).
When the cell is highlighted (goes blue) it makes all the background colors of the UILabels turn clear. I have 2 UILabels where I don't want this to be the case. Currently I'm using UIImageViews behind the UILabel's to make it look like the background color doesn't change. But this seems an inefficient way to do it.
How can i stop certain UILabel's background color changing when the UITableViewCell is highlighted?
You need to subclass UITableViewCell and override the following two methods:
Objective-C:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
UIColor *backgroundColor = self.myLabel.backgroundColor;
[super setHighlighted:highlighted animated:animated];
self.myLabel.backgroundColor = backgroundColor;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
UIColor *backgroundColor = self.myLabel.backgroundColor;
[super setSelected:selected animated:animated];
self.myLabel.backgroundColor = backgroundColor;
}
Swift
override func setSelected(_ selected: Bool, animated: Bool) {
let color = myLabel.backgroundColor
super.setSelected(selected, animated: animated)
myLabel.backgroundColor = color
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
let color = myLabel.backgroundColor
super.setHighlighted(highlighted, animated: animated)
myLabel.backgroundColor = color
}