How can I change color of a section header in UITableView?
EDIT: The answer provided by DJ-S should be considered for iOS 6 and above. The accepted
Just set the background color of the background view:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
let tableHeader = view as! UITableViewHeaderFooterView
tableHeader.backgroundView?.backgroundColor = UIColor.white
}
The following solution works for Swift 1.2 with iOS 8+
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// This changes the header background
view.tintColor = UIColor.blueColor()
// Gets the header view as a UITableViewHeaderFooterView and changes the text colour
var headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
headerView.textLabel.textColor = UIColor.redColor()
}
I got message from Xcode through console log
[TableView] Setting the background color on UITableViewHeaderFooterView has been deprecated. Please set a custom UIView with your desired background color to the backgroundView property instead.
Then I just create a new UIView and lay it as background of HeaderView. Not a good solution but it easy as Xcode said.
You can do it on main.storyboard in about 2 seconds.
Although func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
will work as well, you can acheive this without implementing another delegate method.
in you func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
method, you can use view.contentView.backgroundColor = UIColor.white
instead of view.backgroundView?.backgroundColor = UIColor.white
which is not working. (I know that backgroundView
is optional, but even when it is there, this is not woking without implementing willDisplayHeaderView
SWIFT 2
I was able to successfully change the section background color with an added blur effect (which is really cool). To change the background color of section easily:
Then for blur effect, add to code:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// This is the blur effect
let blurEffect = UIBlurEffect(style: .Light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
// Gets the header view as a UITableViewHeaderFooterView and changes the text colour and adds above blur effect
let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
headerView.textLabel!.textColor = UIColor.darkGrayColor()
headerView.textLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 13)
headerView.tintColor = .groupTableViewBackgroundColor()
headerView.backgroundView = blurEffectView
}