繁体   English   中英

如何以编程方式使用原型单元删除表格视图节标题

[英]how to remove table view section header using prototype cell programmatically

我通过使用这样的原型单元格在界面构建器中设置了表格视图标题部分

在此处输入图片说明

这是此表视图标题部分的最终结果

在此处输入图片说明

数据实际上是动态的,并且如果可用的部分只有一个(比如说财务),我希望表视图标题部分不存在,只需显示人员名称即可。 下面是我使用的简化代码。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var sectionMember : [Department]?

    var abcd = 2


    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self

        let IT = Department(name: "IT", member: ["joko", "santi","pipin","candra"])
        let finance = Department(name: "Finance & Accounting", member: ["ririn","andri","bagus","reyhan"])
        let security = Department(name: "security", member: ["anto","budi","rudi"])
        let purchasing = Department(name: "Purchasing", member: ["lulu","rina","santi"])

        sectionMember = [IT,finance,security, purchasing]
        //sectionMember = [IT]


    }



}

extension ViewController : UITableViewDelegate {

}

extension ViewController : UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return (sectionMember?.count)!
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sectionMember![section].member.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! TableViewCell

        let departmentMember = sectionMember![indexPath.section].member[indexPath.row]

        cell.memberOfDepartment = departmentMember

        return cell
    }


    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {


        if abcd == 1 {
            return nil
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! HeaderCell
            cell.department = sectionMember![section].name
            return cell
        }



    }




}

为了简化代码,我使用变量abcd ,如果abcd = 1我希望该部分标题被隐藏/删除/不存在,但是如果abcd不为1,则显示标题部分。

在方法viewForHeaderInSection ,如果abcd = 1 ,我return nil ,但结果仍然是显示标题部分,但颜色是灰色,我不知道为什么它是灰色而不是情节提要中的粉红色。 那么如何摆脱下面的灰色部分呢?

在此处输入图片说明

在这里,如果只有一个部分,则将标题设为nil,但还要给出高度

 func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

    if sectionMember?.count ?? 0 == 1 {
        return 0.0
    }
    else {
        return your height
    }
}

还有,你的功能

func numberOfSections(in tableView: UITableView) -> Int {
    return (sectionMember?.count)!
}

永远不要这样使用bang运算符。用默认值将其解包

func numberOfSections(in tableView: UITableView) -> Int {
    return self.sectionMember?.count ?? 0
}

暂无
暂无

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

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