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
Swift:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView {
var headerView: TableViewHeader = super.tableView(tableView, viewForHeaderInSection: section) as! TableViewHeader
headerView.backgroundView.backgroundColor = UIColor.redColor()
}
If you are customising a section header cell with Storyboard/Nib, then make sure the background color is default for the "Table Section Header" view.
And if you subclass UITableViewHeaderFooterView
, and using nib, then what you have to do is to create a IBOutlet
for the content view, and name it eg. containerView
. This is not to be confused with contentView
, which is parent of this container view.
With that setup, you change the background color of containerView
instead.
maybe because the backgroundView doesn't exist
override func draw(_ rect: CGRect){
// Drawing code
let view = UIView()
view.frame = rect
self.backgroundView = view
self.backgroundView?.backgroundColor = UIColor.yourColorHere
}
that work for me.
iOS 12, Swift 5. If you are willing (or trying!) to use an appearance proxy, the following solution works:
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
}
}
}
MySectionHeaderView.appearance().forceBackgroundColor = .red
or
MySectionHeaderView.appearance(whenContainedInInstancesOf: [MyOtherClass.self]).forceBackgroundColor = .red
You should either use myTableViewHeaderFooterView.tintColor, or assign a custom background view to myTableViewHeaderFooterView.backgroundView.
On iOS9 headerView.backgroundView.backgroundColor
worked for me:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
TableViewHeader *headerView = (TableViewHeader *)[super tableView:tableView viewForHeaderInSection:section];
headerView.backgroundView.backgroundColor = [UIColor redColor];
}
On iOS8 I was using headerView.contentView.backgroundColor
without problems, but now with iOS 9, I was getting a weird issue that made the background color not fill the whole space of the cell. So I tried just headerView.backgroundColor
and I got the same error from the OP.
Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.
So now everything works great and without warnings by using headerView.backgroundView.backgroundColor