设置自定义UITableViewHeaderFooterView以实现可重用性

时间:2019-04-19 12:05:54

标签: ios swift uitableview

我有一个这样定义和注册的自定义节标题视图:

class MySectionHeaderView : UITableViewHeaderFooterView {
    var section : Int?
    var button : UIButton?
}

class MyTableViewController : UITableViewController {

    override func loadView() {
        super.loadView()
        self.tableView.register(MySectionHeaderView.self,
            forHeaderFooterViewReuseIdentifier: "reuseIdentifier")
    }

    override func tableView(_ tableView: UITableView,
            viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterView(
            withIdentifier: "reuseIdentifier")! as! MySectionHeaderView
        header.textLabel?.text = titleForHeader(section: section)
        header.section = section
        if header.button == nil {
           let button = UIButton(type: .system)
           // ... configure button ... //
           header.button = button
        }
        return header
    }
}

这有效。但是,将按钮和其他初始化器放在函数tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView中是很奇怪的。因为它打破了关注原则的分离。此功能应仅用于设置标签等。

是否可以初始化标题视图,在类MySectionHeaderView内的某个地方创建子元素?

1 个答案:

答案 0 :(得分:1)

仅在viewForHeaderInSection中设置标头的数据源相关信息。将所有设置代码移到自定义标头类中。

class MySectionHeaderView: UITableViewHeaderFooterView {
    var section: Int?
    lazy var button: UIButton = {
        let button = UIButton(type: .system)
           // ... configure button ... //
        return button
    }()

    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)

        //Add subviews and set up constraints
    }
}

现在在您的委托方法中,

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = tableView.dequeueReusableHeaderFooterView(
        withIdentifier: "reuseIdentifier")! as! MySectionHeaderView
    header.textLabel?.text = titleForHeader(section: section)
    header.section = section
    return header
}
相关问题