这是我自定义的UICollectionViewCell代码。我只是在configureViews()函数中给子视图一个约束。
class CategoryCell: UICollectionViewCell {
private lazy var nameLabel: UILabel = {
let label = PaddingLabel()
label.numberOfLines = 1
label.adjustsFontForContentSizeCategory = true
label.font = UIFont.boldSystemFont(ofSize: UIFont.preferredFont(forTextStyle: .subheadline).pointSize)
label.textAlignment = .center
let widthConstant = floor((UIScreen.main.bounds.size.width) / 3)
label.widthAnchor.constraint(equalToConstant: widthConstant).isActive = true
return label
}()
private lazy var bottomLine = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
configureViews()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configureViews()
}
override func prepareForReuse() {
super.prepareForReuse()
nameLabel.text = nil
}
}
private extension CategoryCell {
func configureViews() {
contentView.addSameSizeConstrained(subView: nameLabel)
contentView.addSubview(bottomLine)
bottomLine.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
bottomLine.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
bottomLine.topAnchor.constraint(equalTo: contentView.bottomAnchor),
bottomLine.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
bottomLine.heightAnchor.constraint(equalToConstant: AppLayoutGuidance.spacingHalf / 4),
])
}
}
当单元格第一次呈现时,没有任何问题,但是当我调用collectionView.reloadData()函数时,控制台上出现了一个约束错误。你知道吗?
编辑:约束控制台日志
"<NSLayoutConstraint:0x600000d01090 App.PaddingLabel:0x13d494320.width == 130 (active)>",
"<NSLayoutConstraint:0x600000d010e0 H:|-(0)-[App.PaddingLabel:0x13d494320] (active, names: '|':UIView:0x13d467360 )>",
"<NSLayoutConstraint:0x600000d01130 App.PaddingLabel:0x13d494320.trailing == UIView:0x13d467360.trailing (active)>",
"<NSLayoutConstraint:0x600000d02850 'UIView-Encapsulated-Layout-Width' UIView:0x13d467360.width == 0 (active)>"
1条答案
按热度按时间wkyowqbh1#
我认为addSameSizeConstrained函数,顾名思义,使添加了contentview的视图的框架相同。因此
nameLabel
的width
等于contentView
。但是在定义
label
时,您为标签指定了宽度值floor((UIScreen.main.bounds.size.width) / 3)
UIView-Encapsulated-Layout-Width' UIView:0x13d467360.width == 0
这个消息基本上就是给予我们这个信息。你必须给予priority
一个约束,它们是:floor((UIScreen.main.bounds.size.width) / 3)
addSameSizeConstrained
中的视图宽度您可以通过为其中一个约束指定优先级来修复此问题:
第一次加载时,您不会在控制台中收到此警告,因为collectinview的估计大小必须为
Automatic
。如果使用None
进行更改,则在首次加载时会看到此警告。