如何在 titleForHeaderInSection 中设置颜色? -迅速

问题描述 投票:0回答:2

我的表视图中有两个部分,我想为表视图的不同部分标题设置不同的颜色,我该怎么做?

func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! {
    if (section == 0) {
        return "Item1"
    }
    if (section == 1) {
        return "Item2"
    }
}
swift tableview
2个回答
5
投票

与 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
}

3
投票

斯威夫特 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
}
© www.soinside.com 2019 - 2024. All rights reserved.