UITableViewHeaderFooterView: Unable to change background color
Solution 1:
iOS 8, 9, 10, 11...
The only way to set any color (with any alpha) is to use backgroundView
:
Swift
self.backgroundView = UIView(frame: self.bounds)
self.backgroundView.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
Obj-C
self.backgroundView = ({
UIView * view = [[UIView alloc] initWithFrame:self.bounds];
view.backgroundColor = [UIColor colorWithWhite: 0.5 alpha:0.5];
view;
});
Responses to Comments
-
None of these other options reliably work (despite the comments below)
// self.contentView.backgroundColor = [UIColor clearColor]; // self.backgroundColor = [UIColor clearColor]; // self.tintColor = [UIColor clearColor];
the
backgroundView
is resized automatically. (No need to add constraints)Control alpha with
UIColor(white: 0.5, alpha: 0.5)
orbackgroundView.alpha = 0.5
.
(of course, any color will do)-
When using XIB, make root view a
UITableViewHeaderFooterView
and associate thebackgroundView
programmatically:Register with:
tableView.register(UINib(nibName: "View", bundle: nil), forHeaderFooterViewReuseIdentifier: "header")
Load with:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") { let backgroundView = UIView(frame: header.bounds) backgroundView.backgroundColor = UIColor(white: 0.5, alpha: 0.5) header.backgroundView = backgroundView return header } return nil }
↻ replay animation
► Find this solution on GitHub and additional details on Swift Recipes.
Solution 2:
You should either use myTableViewHeaderFooterView.tintColor
, or assign a custom background view to myTableViewHeaderFooterView.backgroundView
.
Solution 3:
In iOS 7 contentView.backgroundColor
worked for me, tintColor
did not.
headerView.contentView.backgroundColor = [UIColor blackColor];
Though clearColor
did not work for me, the solution I found is to set backgroundView
property to transparent image. Maybe it will help someone:
UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 1), NO, 0.0);
UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
headerView.backgroundView = [[UIImageView alloc] initWithImage:blank];