简体   繁体   中英

Label background colour changed when UITableViewCell selected

I have added a custom label in UITableViewCell. Its background color is red and the font is white. When I select any cell then selected cell's label background color changed into grey.

For reference, I am adding code

let lblUnreadCount = cell?.viewWithTag(3) as! UILabel
let size:CGFloat = 20.0
lblUnreadCount.bounds = CGRect(x: 0.0, y: 0.0, width: 28.0, height: 20.0)
lblUnreadCount.layer.cornerRadius = size / 2
lblUnreadCount.layer.borderWidth = 1.0
lblUnreadCount.layer.backgroundColor = UIColor.red.cgColor
lblUnreadCount.layer.borderColor = UIColor.red.cgColor

For reference, I am also adding a screenshot. 在此处输入图片说明

It's not the label's background that's changing but the cell itself. In your cellForRow method, after you've dequeued the cell, use this

cell.selectionStyle = .none

Seems like setting cell style to .none is not what OP wanted as it actually clears the cell's highlighted color when selected.

I found it a bit tricky to achieve like this (clear the TextLabel bg color and set the bg color to its layer):

// Note that cell background color must be cleared **before** setting layer color
lblUnreadCount.backgroundColor = UIColor.clear
lblUnreadCount.layer.backgroundColor = UIColor.red.cgColor

This way you will be able to keep the bg color of the text label (within the cell) unchanged when the cell is selected and highlighted.

1.set selection style none

UITableViewCell | |----- UIView | |-----UIImageView-> eg:Message icon |-----Title Label-> eg:Message |-----Count Label-> red background

2.when cell is selected you have to change the UIView background color(gray).

set background color of your label inside UITableViewCell.In above code you set the label's layer background color.

lblUnreadCount.backgroundColor = UIColor.red.cgColor

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM