Change the sections header background color in UITableView using an array of headers
Solution 1:
If you're using only titleForHeaderInSection :
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
(view as! UITableViewHeaderFooterView).contentView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
(view as! UITableViewHeaderFooterView).textLabel?.textColor = UIColor.white
}
Solution 2:
Instead of using the
func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String?
data source method, you can use the
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
delegate method and simply customize the UIView
returned as you wish.
For example set the text of the UILabel
textLabel
to your desired value and the backgroundColor
to the desired UIColor
.
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let returnedView = UIView(frame: CGRectMake(x, y, width, height)) //set these values as necessary
returnedView.backgroundColor = UIColor.lightGrayColor()
let label = UILabel(frame: CGRectMake(labelX, labelY, labelWidth, labelHeight))
label.text = self.sectionHeaderTitleArray[section]
returnedView.addSubview(label)
return returnedView
}
SWIFT 5
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let returnedView = UIView(frame: CGRect(x: x, y: y, width: width, height: height)) //set these values as necessary
returnedView.backgroundColor = .white
let label = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
label.text = self.sectionHeaderTitleArray[section]
returnedView.addSubview(label)
return returnedView
}