Высота раздела заголовка UITableView не настраивается автоматически для пользовательского класса UIView () - PullRequest
0 голосов
/ 26 января 2019

У меня есть класс UIView (), в котором я добавляю метку программно, а также имею ограничения для автоматической настройки высоты просмотра на основе содержимого.Я использовал этот класс в качестве HeaderView для раздела UItableView.Но проблема здесь в том, что высота этого представления не корректируется в соответствии с его содержимым.

Вот мой код этого пользовательского представления.

class DynamicHeaderView: UIView {

override func draw(_ rect: CGRect) {
    let headerLabel = UILabel()
    headerLabel.numberOfLines = 0
    headerLabel.sizeToFit()
    headerLabel.text = "This is header view. It is dynamicaaly growing text and will automaticaly get adjusted to it"
    self.backgroundColor = .green
    headerLabel.translatesAutoresizingMaskIntoConstraints = false

    self.addSubview(headerLabel)

    self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 16))

    self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: -16))

    self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 10))

    self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: -10))
} }

Код, который я написал в моемviewController,

 override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.countriesTable.sectionHeaderHeight = UITableView.automaticDimension;
    self.countriesTable.estimatedSectionHeaderHeight = 25 }

 func tableView(_ tableView: UITableView,
               viewForHeaderInSection section: Int) -> UIView? {
    let headerView = DynamicHeaderView()
    return headerView
}

Высота всегда соответствует предполагаемой высоте заголовка как 25, которую я дал в функции viewDidLoad ().

1 Ответ

0 голосов
/ 26 января 2019

Вам нужно создать подкласс UITableViewHeaderFooterView, затем зарегистрировать в нем tableView, наконец, реализовать viewForHeaderInSection

class DynamicHeaderView: UITableViewHeaderFooterView {

    let headerLabel = UILabel()

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

        headerLabel.numberOfLines = 0
     //   headerLabel.sizeToFit()
        headerLabel.text = "This is header view. It is dynamicaaly growing text and will automaticaly get adjusted to it"
        self.backgroundColor = .green
        headerLabel.translatesAutoresizingMaskIntoConstraints = false

        self.addSubview(headerLabel)

        headerLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .vertical)

        self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 16))

        self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: -16))

        self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 10))

        self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 10))
    }



    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

//

В viewDidLoad

 tableView.register(DynamicHeaderView.self, forHeaderFooterViewReuseIdentifier: "celld")  

 tableView.estimatedSectionHeaderHeight = 50 

 tableView.sectionHeaderHeight = UITableView.automaticDimension

//

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

    let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "celld") as! DynamicHeaderView


    headerView.headerLabel.text = "heightForHeaderInSectionheightForHeaderInSectionheightForHeaderInSectionheightForHeaderInSectionheightForHeaderInSectionheightForHeaderInSection"

    return headerView
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...