这是我自定义的 UICollectionViewCell 代码。我只是在 configureViews() 函数中给子视图一个约束。
class CategoryCell: UICollectionViewCell {
private lazy var containerStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .fill
stackView.distribution = .fill
stackView.spacing = AppLayoutGuidance.spacingHalf
let widthConstant = floor((UIScreen.main.bounds.size.width) / 3)
NSLayoutConstraint.activate([
stackView.widthAnchor.constraint(equalToConstant: widthConstant),
])
return stackView
}()
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
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: containerStackView)
containerStackView.addArrangedSubview(nameLabel)
containerStackView.addArrangedSubview(bottomLine)
bottomLine.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
bottomLine.heightAnchor.constraint(equalToConstant: AppLayoutGuidance.spacingHalf / 4),
])
}
}
cell第一次渲染的时候没有问题,但是调用collectionView.reloadData()函数的时候,console出现constraint error。你有什么想法吗?