Search code examples
swiftuitableviewuikit

How to set a color in titleForHeaderInSection?


I have two sections in my tableview and I want to set a different colour for different sectionHeaders of the tableView. How can I do that?

func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! {
    if (section == 0) {
        return "Item1"
    }
    if (section == 1) {
        return "Item2"
    }
}

Solution

  • in the same way as in Objective-C: providing a custom header with a label and change it's text color

    override func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
        var label : UILabel = UILabel()
        if(section == 0){
            label.text = "Item1"
        } else if (section == 1){
            label.textColor = UIColor.orangeColor()
            label.text = "Item2"
        }
        return label
    }