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
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
}
}
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