我的表视图中有两个部分,我想为表视图的不同部分标题设置不同的颜色。我怎样才能做到这一点?
func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! {
if (section == 0) {
return "Item1"
}
if (section == 1) {
return "Item2"
}
}
与 Objective-C 中的方式相同:提供带有标签的自定义标题并更改其文本颜色
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
}
斯威夫特 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
}
不要忘记设置视图的高度
func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return 50
}