UITableView с automaticDimension не динамически увеличивает размер из-за ошибки NSLayoutConstraint - PullRequest
0 голосов
/ 25 марта 2019

Я создаю кастом UITableViewCell.Пока все, что я хочу, это чтобы UIButton слева (checkButton) и два UILabel s (titleLabel и notesLabel) справа от кнопки.

По сути, он должен выглядеть как стандартный UITableViewCell с изображением и двумя текстовыми метками (но, пожалуйста, не говорите мне просто повторно использовать стандартную ячейку, потому что я не могу сделать это по разным причинам),Кнопка должна иметь фиксированный размер (16x16) и быть вертикально центрированной в ячейке.Эти две метки должны быть перенесены и расширены, чтобы соответствовать их содержанию.Я пытаюсь определить эту ячейку программно, поэтому я создал приведенный ниже инициализатор для определения ограничений.

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.font = UIFont.systemFont(ofSize: 16)
    titleLabel.lineBreakMode = .byWordWrapping
    titleLabel.numberOfLines = 0
    contentView.addSubview(titleLabel)
    checkButton.translatesAutoresizingMaskIntoConstraints = false
    contentView.addSubview(checkButton)
    notesLabel.translatesAutoresizingMaskIntoConstraints = false
    notesLabel.font = UIFont.systemFont(ofSize: 13)
    notesLabel.lineBreakMode = .byWordWrapping
    notesLabel.numberOfLines = 0
    contentView.addSubview(notesLabel)
    addConstraint(NSLayoutConstraint(item: titleLabel,
                                     attribute: .top,
                                     relatedBy: .equal,
                                     toItem: contentView,
                                     attribute: .top,
                                     multiplier: 1,
                                     constant: 0))
    addConstraint(NSLayoutConstraint(item: notesLabel,
                                     attribute: .top,
                                     relatedBy: .equal,
                                     toItem: titleLabel,
                                     attribute: .bottom,
                                     multiplier: 1,
                                     constant: 0))
    addConstraint(NSLayoutConstraint(item: titleLabel,
                                     attribute: .trailing,
                                     relatedBy: .equal,
                                     toItem: contentView,
                                     attribute: .trailing,
                                     multiplier: 1,
                                     constant: -10))
    addConstraint(NSLayoutConstraint(item: notesLabel,
                                     attribute: .trailing,
                                     relatedBy: .equal,
                                     toItem: contentView,
                                     attribute: .trailing,
                                     multiplier: 1,
                                     constant: -10))
    addConstraint(NSLayoutConstraint(item: notesLabel,
                                     attribute: .bottom,
                                     relatedBy: .equal,
                                     toItem: contentView,
                                     attribute: .bottom,
                                     multiplier: 1,
                                     constant: 0))
    addConstraint(NSLayoutConstraint(item: checkButton,
                                     attribute: .leading,
                                     relatedBy: .equal,
                                     toItem: contentView,
                                     attribute: .leading,
                                     multiplier: 1,
                                     constant: 20))
    addConstraint(NSLayoutConstraint(item: checkButton,
                                     attribute: .centerY,
                                     relatedBy: .equal,
                                     toItem: contentView,
                                     attribute: .centerY,
                                     multiplier: 1,
                                     constant: 0))
    addConstraint(NSLayoutConstraint(item: checkButton,
                                     attribute: .height,
                                     relatedBy: .equal,
                                     toItem: nil,
                                     attribute: .notAnAttribute,
                                     multiplier: 0,
                                     constant: 16))
    addConstraint(NSLayoutConstraint(item: checkButton,
                                     attribute: .width,
                                     relatedBy: .equal,
                                     toItem: nil,
                                     attribute: .notAnAttribute,
                                     multiplier: 0,
                                     constant: 16))
    addConstraint(NSLayoutConstraint(item: notesLabel,
                                     attribute: .leading,
                                     relatedBy: .equal,
                                     toItem: checkButton,
                                     attribute: .trailing,
                                     multiplier: 1,
                                     constant: 12))
    addConstraint(NSLayoutConstraint(item: titleLabel,
                                     attribute: .leading,
                                     relatedBy: .equal,
                                     toItem: checkButton,
                                     attribute: .trailing,
                                     multiplier: 1,
                                     constant: 12))
}

Когда я запускаю этот код, он работает в основном так, как ожидается, за исключением того, что Xcode печатает следующеепредупреждение: [Warning] Warning once only: Detected a case where constraints ambiguously suggest a height of zero for a tableview cell's content view. We're considering the collapse unintentional and using standard height instead.

Обычно я просто игнорирую это, но, похоже, препятствует расширению ячейки до ее содержимого.Например, если у одной из меток достаточно содержимого для расширения до 3 строк, отображается только первая строка.Я хочу, чтобы метки (и, соответственно, ячейка) расширялись, чтобы соответствовать их содержанию.Что я делаю не так с ограничениями по высоте?

Ответы [ 2 ]

1 голос
/ 25 марта 2019

ПРИМЕЧАНИЕ: Пожалуйста, добавьте ваши метки и кнопки в ячейку, а не в contentView ячейки. код ниже будет работать, пожалуйста, проверьте и дайте мне знать, если возникли проблемы.

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

    addSubview(titleLabel)
    addSubview(checkButton)
    addSubview(notesLabel)

    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.font = UIFont.systemFont(ofSize: 16)
    titleLabel.lineBreakMode = .byWordWrapping
    titleLabel.numberOfLines = 0

    checkButton.translatesAutoresizingMaskIntoConstraints = false

    notesLabel.translatesAutoresizingMaskIntoConstraints = false
    notesLabel.font = UIFont.systemFont(ofSize: 13)
    notesLabel.lineBreakMode = .byWordWrapping
    notesLabel.numberOfLines = 0

    addConstraint(NSLayoutConstraint(item: titleLabel,
                                     attribute: .top,
                                     relatedBy: .equal,
                                     toItem: self,
                                     attribute: .top,
                                     multiplier: 1,
                                     constant: 0))
    addConstraint(NSLayoutConstraint(item: notesLabel,
                                     attribute: .top,
                                     relatedBy: .equal,
                                     toItem: titleLabel,
                                     attribute: .bottom,
                                     multiplier: 1,
                                     constant: 0))
    addConstraint(NSLayoutConstraint(item: titleLabel,
                                     attribute: .trailing,
                                     relatedBy: .equal,
                                     toItem: self,
                                     attribute: .trailing,
                                     multiplier: 1,
                                     constant: -10))
    addConstraint(NSLayoutConstraint(item: notesLabel,
                                     attribute: .trailing,
                                     relatedBy: .equal,
                                     toItem: self,
                                     attribute: .trailing,
                                     multiplier: 1,
                                     constant: -10))
    addConstraint(NSLayoutConstraint(item: notesLabel,
                                     attribute: .bottom,
                                     relatedBy: .equal,
                                     toItem: self,
                                     attribute: .bottom,
                                     multiplier: 1,
                                     constant: 0))
    addConstraint(NSLayoutConstraint(item: checkButton,
                                     attribute: .leading,
                                     relatedBy: .equal,
                                     toItem: self,
                                     attribute: .leading,
                                     multiplier: 1,
                                     constant: 20))
    addConstraint(NSLayoutConstraint(item: checkButton,
                                     attribute: .centerY,
                                     relatedBy: .equal,
                                     toItem: self,
                                     attribute: .centerY,
                                     multiplier: 1,
                                     constant: 0))
    addConstraint(NSLayoutConstraint(item: checkButton,
                                     attribute: .height,
                                     relatedBy: .equal,
                                     toItem: nil,
                                     attribute: .notAnAttribute,
                                     multiplier: 0,
                                     constant: 16))
    addConstraint(NSLayoutConstraint(item: checkButton,
                                     attribute: .width,
                                     relatedBy: .equal,
                                     toItem: nil,
                                     attribute: .notAnAttribute,
                                     multiplier: 0,
                                     constant: 16))
    addConstraint(NSLayoutConstraint(item: notesLabel,
                                     attribute: .leading,
                                     relatedBy: .equal,
                                     toItem: checkButton,
                                     attribute: .trailing,
                                     multiplier: 1,
                                     constant: 12))
    addConstraint(NSLayoutConstraint(item: titleLabel,
                                     attribute: .leading,
                                     relatedBy: .equal,
                                     toItem: checkButton,
                                     attribute: .trailing,
                                     multiplier: 1,
                                     constant: 12))
}
0 голосов
/ 25 марта 2019

Вот мой подход

private func setUp() {
    self.selectionStyle = .none
    self.contentView.backgroundColor = .white

    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 16, height: 16))
    button.setImage(UIImage(named: "arrow"), for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    self.contentView.addSubview(button)
    button.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 8.0).isActive = true
    button.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true
    button.widthAnchor.constraint(equalToConstant: button.frame.width).isActive = true
    button.heightAnchor.constraint(equalToConstant: button.frame.height).isActive = true

    let view = UIView()
    view.backgroundColor = .red
    view.translatesAutoresizingMaskIntoConstraints = false
    self.contentView.addSubview(view)
    view.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 8.0).isActive = true
    view.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: button.frame.width + 16.0).isActive = true
    view.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: 8.0).isActive = true
    view.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -8.0).isActive = true

    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.numberOfLines = 0
    view.addSubview(titleLabel)
    titleLabel.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true

    notesLabel.translatesAutoresizingMaskIntoConstraints = false
    notesLabel.numberOfLines = 0
    view.addSubview(notesLabel)
    notesLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8.0).isActive = true
    notesLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    notesLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    notesLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}

Если метки имеют многострочную динамическую высоту, используйте следующие для включения ячеек с саморазмером

tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44.0

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

Это дает

enter image description here

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