【问题标题】:How to set specific section header in UITableView [Swift]如何在 UITableView [Swift] 中设置特定的节标题
【发布时间】:2019-05-29 18:01:07
【问题描述】:

我想以编程方式将节标题添加到我的 UITableView 的一个部分。

我正在尝试使用此代码,但它会将标题添加到所有部分。我怎样才能让它只设置第一节的标题?

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "My Section header"
}

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    这样做

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0{ // <- apply condition where you wanted to show header or not.
            return "My Section header"
        }
        return nil
    }
    

    【讨论】:

      【解决方案2】:

      你只需要检查部分是否等于一

       override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
          return (section == 1) ? "Title Header" : nil
      }
      

      【讨论】:

      • 索引从 0 而不是 1 开始。
      • 必须是section.count == 1
      【解决方案3】:

      使用 switch-case 编写更好的代码

      func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
           switch section {
           case 0: return "Section 0"
           case 1: return "Section 1"
           default: return nil
           }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-03-22
        • 1970-01-01
        • 2012-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多