настроить пользовательский UITableViewHeaderFooterView для повторного использования - PullRequest
1 голос
/ 19 апреля 2019

У меня есть пользовательский вид заголовка раздела, определенный и зарегистрированный так:

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 Ответ

1 голос
/ 19 апреля 2019

Устанавливать только заголовочную информацию, зависящую от источника данных, в 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
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...