Jp4Real Jp4Real - 1 month ago 10
Swift Question

Change the sections header background color in UITableView using an array of headers

I have a array of headers that I use

let sectionHeaderTitleArray = ["test1","test2","test3]


and they are showed using

func tableView[tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section] as String
}


Now all of this works fine but I would like to modify the background color of the headers so that they are more visible (Darker Color)

any idea if I can do this in a simple line or do I need to use a custom cell to create this

thanks

update

//number of sections and names for the table

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.sectionHeaderTitleArray.count
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section] as String
}
func tableView(tableView: UITableView, ViewForHeaderInSection section: Int) -> UIView? {
return self.tableView.backgroundColor = UIColor.lightGrayColor()
}

Answer

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? {
    var returnedView = UIView(frame: CGRectMake(x, y, width, height)) //set these values as necessary
    returnedView.backgroundColor = UIColor.lightGrayColor()

    var label = UILabel(frame: CGRectMake(labelX, labelY, labelWidth, labelHeight))
    label.text = self.sectionHeaderTitleArray[section]
    returnedView.addSubview(label)

    return returnedView
}