Саморазмерящаяся ячейка отрисовывается с неверной высотой при первой раскладке
Эта ячейка должна подстраивать высоту под метку, но каждая строка рисуется на оценочной высоте, а не на реальной. Таблица задаёт estimatedRowHeight = 44 и rowHeight = .automaticDimension.
Найдите и исправьте ошибку в constraint'ах ячейки.
final class ProductCell: UITableViewCell {
let title = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
title.numberOfLines = 0
title.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(title)
NSLayoutConstraint.activate([
title.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12),
title.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
title.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
])
}
required init?(coder: NSCoder) { fatalError() }
}
Найдите и исправьте ошибку.
title закреплён сверху, слева и справа, но не к contentView.bottomAnchor, поэтому вертикальная цепочка не доходит до низа и высота ячейки неоднозначна, оставаясь на оценке. Добавьте недостающий нижний constraint, чтобы высота шла из содержимого.
- ✗Оставляют разрыв в цепочке constraint'ов от верха до низа contentView
- ✗Принимают оценку за финальную высоту, а не за заглушку
- ✗Винят тайминг reload вместо неоднозначных вертикальных constraint'ов
- →Почему цепочка должна доходить именно до
contentView.bottomAnchor, а не ячейки? - →Как
numberOfLines = 0у многострочной метки взаимодействует с этой цепочкой?
The cell can't be measured because its vertical constraints stop at the label's top: nothing ties title's bottom to contentView.bottomAnchor, so the content view has no way to derive its own height. Auto Layout marks the height ambiguous and the table keeps the 44-pt estimate. The fix is to close the top-to-bottom chain:
NSLayoutConstraint.activate([
title.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12),
title.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
title.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
// the missing rung — now content height flows to the cell:
title.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -12),
])
With estimatedRowHeight > 0 and rowHeight = .automaticDimension already set, the completed chain lets a multiline label (numberOfLines = 0) grow and push the cell to its true height. The estimate only seeds the initial scroll metrics; the constraint chain produces the final size.