UITableViewHeaderFooterView: Unable to change background color

前端 未结 20 2253
误落风尘
误落风尘 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
        }
    }
    

提交回复
热议问题