简体   繁体   中英

Setting UITableViewCell selected background color with UIAppearence not working

I want to change the selected color of all my UITableViewCell s. I am already using UIAppearence to define basic properties for some other UI elements and it works.

However, setting

let bgColorView = UIView()
bgColorView.backgroundColor = #colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9411764706, alpha: 1)
UITableViewCell.appearance().selectedBackgroundView = bgColorView

Results in a strange glitch, the cell losing the selection color, although the UITableViewCell s is still selected:

UITableViewCell消失的选择

The glitch is not caused by UI code because setting the selected color directly in UITableViewCell.awakeFromNib works fine, the selected cell stays the desired color.

Edit : This happens with all the different cells. The cells do not do anything interesting, just set stuff like label colors, etc in awakeFromNib and some RxSwift binding in a model setter to set the values of the various labels. The VCs just react to the cell getting selected by calling a delegate method (using modelSelected from RxSwift ).

Edit : The VC with the UITableView is the "left side" of a UISplitViewController . The "right side" is a UINavigationController and navigation in this UINavigationController using setViewControllers after tapping the cell causes the strange glitch.

So after some investigations I was able to reproduce your "glitch" :) I downloaded RxSwift and then tried their tableView sample. I use RxSwift too but I don't use their tableView delegate/datasource extensions. I also made a custom tableViewCell.

After overriding the setSelected method of the UITableViewCell , and not calling its super method, the same case happened. Actually, even without using RxSwift, this should happen.

So again, make sure in your tableView class, if you do not need to do anything with setSelected , don't override it. Otherwise, when overriding super class methods, make sure you're calling the super.method(), just like what you're doing in your controller's viewDidLoad() .

override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
}

It should work perfectly fine, I have tried in an iOS application.

Try using a different color for the selected background, It might be same as you cell's background color

And verify that UITableViewCell#selection property is not set to none

在此处输入图片说明

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