UITableViewHeaderFooterView: Unable to change background color

前端 未结 20 2234
误落风尘
误落风尘 2020-12-23 08:38

I\'m trying to change the background color of UITableViewHeaderFooterView. Although the view is appearing, the background color remains the default color. I\'m getting a log

20条回答
  •  爱一瞬间的悲伤
    2020-12-23 09:26

    iOS 12, Swift 5. If you are willing (or trying!) to use an appearance proxy, the following solution works:

    1. Subclass UITableViewHeaderFooterView and expose your own appearance proxy setting.
    final class MySectionHeaderView: UITableViewHeaderFooterView {
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    
        override init(reuseIdentifier: String?) {
            super.init(reuseIdentifier: reuseIdentifier)
        }
    
        @objc dynamic var forceBackgroundColor: UIColor? {
            get { return self.contentView.backgroundColor }
            set(color) {
                self.contentView.backgroundColor = color
                // if your color is not opaque, adjust backgroundView as well
                self.backgroundView?.backgroundColor = .clear
            }
        }
    }
    
    1. Set the appearance proxy at your desired granularity.
    MySectionHeaderView.appearance().forceBackgroundColor = .red
    

    or

    MySectionHeaderView.appearance(whenContainedInInstancesOf: [MyOtherClass.self]).forceBackgroundColor = .red
    

提交回复
热议问题