swift reloadData后UICollectionViewCell约束错误

rmbxnbpk  于 2023-05-16  发布在  Swift
关注(0)|答案(1)|浏览(124)

这是我自定义的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)>"
wkyowqbh

wkyowqbh1#

我认为addSameSizeConstrained函数,顾名思义,使添加了contentview的视图的框架相同。因此nameLabelwidth等于contentView
但是在定义label时,您为标签指定了宽度值floor((UIScreen.main.bounds.size.width) / 3)
UIView-Encapsulated-Layout-Width' UIView:0x13d467360.width == 0这个消息基本上就是给予我们这个信息。你必须给予priority一个约束,它们是:

  • 声明中的nameLabel宽度约束= floor((UIScreen.main.bounds.size.width) / 3)
  • 名称相等内容中的标签宽度约束addSameSizeConstrained中的视图宽度

您可以通过为其中一个约束指定优先级来修复此问题:

let widthConstant = floor((UIScreen.main.bounds.size.width) / 3)
let const = label.widthAnchor.constraint(equalToConstant: widthConstant)
   const.priority = .defaultLow
   const.isActive = true
return label

第一次加载时,您不会在控制台中收到此警告,因为collectinview的估计大小必须为Automatic。如果使用None进行更改,则在首次加载时会看到此警告。

相关问题