UITableView automati c измерение не работает: ошибка UIView-Encapsulated-Layout-Height - PullRequest
0 голосов
/ 27 февраля 2020

Я пытаюсь внедрить ячейку таблицы размеров для самостоятельного определения размера. Я устанавливаю высоту автооткрытия внутри ячейки, но она показывает ошибку авторазметки.

Я устанавливаю translatesAutoresizingMaskIntoConstraints = false и устанавливаю UITableView.autoDimension.

Это показывает ошибку автооткрытия, как показано ниже.

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x6000024ce9e0 DisposeSecond.MyCell:0x7f9ba7104aa0'cell'.height == 100   (active)>",
    "<NSLayoutConstraint:0x6000024ce800 'UIView-Encapsulated-Layout-Height' DisposeSecond.MyCell:0x7f9ba7104aa0'cell'.height == 100.333   (active)>"
)


Моя реализация довольно проста.


import UIKit

class MyCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        translatesAutoresizingMaskIntoConstraints = false
        self.heightAnchor.constraint(equalToConstant: 100).isActive = true

        // Set debug colors to visualize heigh
        layer.borderWidth = 2
        layer.borderColor = UIColor.blue.cgColor
    }

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

class MyTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(MyCell.self, forCellReuseIdentifier: "cell")
    }


    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 30
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyCell
        return cell
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // I know it is set automatically but just indeed
        return UITableView.automaticDimension
    }
}

1 Ответ

1 голос
/ 27 февраля 2020

Первая проблема: как правило, вы никогда не должны изменять вид ячейки , например:

    translatesAutoresizingMaskIntoConstraints = false
    self.heightAnchor.constraint(equalToConstant: 100).isActive = true

, вместо этого изменяйте ячейку содержимое :

   contentView.heightAnchor.constraint(equalToConstant: 100.0).isActive = true

Далее, при использовании ячеек автоматического изменения размера и табличных представлений (или представлений коллекции), автоматическое расположение часто сталкивается с конфликтами, поскольку оно делает несколько проходов. Это связано с такими вещами, как разделители, размеры объекта и т. Д. c.

Этого можно избежать, используя priority из 999 в ограничениях вместо значения по умолчанию 1000:

    // create heightAnchor for contentView
    let c = contentView.heightAnchor.constraint(equalToConstant: 100.0)
    // set priority to 999 to avoid auto-layout conflicts with auto-sizing cells
    c.priority = UILayoutPriority(rawValue: 999)
    // activate it
    c.isActive = true

В-третьих, реализация heightForRowAt почти никогда не требуется при использовании ячеек автоматического размещения и автоматического изменения размера. Если вы не знаете конкретно , почему вам нужно это реализовать, не надо.

Вот класс вашей ячейки, модифицированный с помощью приведенных выше примечаний:

class MyCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        // never modify self in this way
        //translatesAutoresizingMaskIntoConstraints = false
        //self.heightAnchor.constraint(equalToConstant: 100).isActive = true

        // create heightAnchor for contentView
        let c = contentView.heightAnchor.constraint(equalToConstant: 100.0)
        // set priority to 999 to avoid auto-layout conflicts with auto-sizing cells
        c.priority = UILayoutPriority(rawValue: 999)
        // activate it
        c.isActive = true

        // Set debug colors to visualize heigh
        layer.borderWidth = 2
        layer.borderColor = UIColor.blue.cgColor
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...