UITableViewHeaderFooterView: Unable to change background color

前端 未结 20 2098
误落风尘
误落风尘 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:31

    Forget about difficulties.

    Add to your project UITableViewHeaderFooterView+BGUpdate.swift with code below:

    extension UITableViewHeaderFooterView {
    
        open override var backgroundColor: UIColor? {
            get {
                return self.backgroundColor
            }
            set {
                let bgView = UIView()
                bgView.backgroundColor = newValue
                backgroundView = bgView
            }
        }
    }
    

    Usage is simple as you expected before:

    headerView.backgroundColor = .red
    

    Usage examples:

    1) In delegate's tableView:viewForHeaderInSection: :

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = tv.dequeueReusableHeaderFooterView(withIdentifier: "MyHeaderView")
        headerView.backgroundColor = .red // <- here
        return headerView
    }
    

    or

    2) In your custom header view class:

    class MyHeaderView: UITableViewHeaderFooterView {
    
        override func awakeFromNib() {
            super.awakeFromNib()
            backgroundColor = .red // <- here
        }
    }
    
    0 讨论(0)
  • 2020-12-23 09:34

    For solid background colors, setting the contentView.backgroundColor should be enough:

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        if let headerView = view as? UITableViewHeaderFooterView {
            headerView.contentView.backgroundColor = .red // Works!
        }
    }
    

    For colors with transparency, including .clear color, this no longer works:

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        if let headerView = view as? UITableViewHeaderFooterView {
            headerView.contentView.backgroundColor = .clear // Does not work                                                                     
    0 讨论(0)
提交回复
热议问题