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"
}
}
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With