AutoSizing单元格:单元格宽度等于CollectionView

Ric*_*hiy 5 autosize ios autolayout uicollectionview swift

我正在使用Autolayout和UICollectionView的AutoSizing单元格.

我可以在单元初始化的代码中指定约束:

  func configureCell() {
    snp.makeConstraints { (make) in
      make.width.equalToSuperview()
    }
  }
Run Code Online (Sandbox Code Playgroud)

然而,应用程序崩溃,因为单元格尚未添加到collectionView.

问题

  1. cell生命周期的哪个阶段,可以用cell's width?添加约束?

  2. 有没有作出任何默认方式cellwidthequal to the of the的CollectionView without accessing an instance of UIScreen orUIWindow`?

编辑 问题不重复,因为它不是关于如何使用AutoSizing单元格功能,而是在单元生命周期的哪个阶段应用约束以使用AutoLayout 实现所需的结果.

Oli*_*son 33

要实现自我调整大小的集合视图单元,您需要做两件事:

  1. 指定estimatedItemSize有关UICollectionViewFlowLayout
  2. preferredLayoutAttributesFitting(_:)在您的手机上实施

1.指定estimatedItemSize有关UICollectionViewFlowLayout

此属性的默认值为CGSizeZero.将其设置为任何其他值会导致集合视图使用单元格的preferredLayoutAttributesFitting(_ :)方法查询每个单元格的实际大小.如果所有单元格的高度相同,请使用itemSize属性而不是此属性来指定单元格大小.

只是一个用于计算滚动视图内容大小的估计值,将其设置为合理的值.

let collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewFlowLayout.estimatedItemSize = CGSize(width: collectionView.frame.width, height: 100)
Run Code Online (Sandbox Code Playgroud)

2. preferredLayoutAttributesFitting(_:)UICollectionViewCell子类上实现

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    let autoLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)

    // Specify you want _full width_
    let targetSize = CGSize(width: layoutAttributes.frame.width, height: 0)

    // Calculate the size (height) using Auto Layout
    let autoLayoutSize = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.defaultLow)
    let autoLayoutFrame = CGRect(origin: autoLayoutAttributes.frame.origin, size: autoLayoutSize)

    // Assign the new size to the layout attributes
    autoLayoutAttributes.frame = autoLayoutFrame
    return autoLayoutAttributes
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回答,这是我尚未实现的第2部分。使用这种方法,多任务应该可以正常工作,并且不需要使用虚拟单元方法。我已经更新了您的答案,以匹配最新的Swift语法。 (2认同)