【问题标题】:How to Set a color in a titleForHeaderInSection? -swift如何在 titleForHeaderInSection 中设置颜色? -迅速
【发布时间】:2023-03-14 07:40:01
【问题描述】:

我的 tableview 中有两个部分,我想为 tableView 的不同 sectionHeaders 设置不同的颜色,我该怎么做?

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

【问题讨论】:

    标签: swift tableview


    【解决方案1】:

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

    【讨论】:

    • 我是否必须写一个 if 语句说 (section == 1) 然后写你刚刚提供的代码??
    • 嘿,我阅读并实现了代码,但我不明白为什么在这个函数中我们需要使用标签。如果我要更改的是我的 headerinsection 中的颜色而不是文本...还是我错了?
    • 一个字符串不知道如何显示自己。 tat 是标签的任务。
    • 是否可以更改标题中的背景颜色??
    • 你介意告诉我怎么做吗?我输入 HeaderView.setbackgroundColor 及其错误...
    【解决方案2】:

    斯威夫特 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-19
      • 1970-01-01
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多