简体   繁体   English

如何在UITableView中设置特定的节标题[Swift]

[英]How to set specific section header in UITableView [Swift]

I want to add a section header to a section of my UITableView programmatically. 我想以编程方式将节标题添加到UITableView的节中。

I'm trying to use this code, but it adds the header to all sections. 我正在尝试使用此代码,但是它将标头添加到所有部分。 How can I make it only set the first section's header? 如何仅设置第一部分的标题?

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

Do like this 像这样

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
}

Use switch-case makes better code 使用开关盒可以编写更好的代码

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

You just have to check the section is equal to one 您只需要检查部分等于一

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM