Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Set a color in a titleForHeaderInSection? -swift

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"
    }
}
like image 842
Joseandy10 Avatar asked Mar 18 '23 10:03

Joseandy10


2 Answers

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
}
like image 127
vikingosegundo Avatar answered Mar 20 '23 23:03

vikingosegundo


Swift 5.1

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 0 {
        return "Section 1"
    } else {
        return "Section 2"
    }
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let label = UILabel()

    if section == 0 {
        label.text = "Sectionn 1"
    } else {
        label.text = "Section 2"
    }

    return label

}

and don't forget to set height for the view

func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
    return 50
}
like image 23
Ahmed Safadi Avatar answered Mar 20 '23 23:03

Ahmed Safadi