![](/img/trans.png)
[英]Autosizing collectionview cell not proper display with minimum line space
[英]AutoSizing cells: cell width equal to the CollectionView
我正在使用Autolayout和UICollectionView的AutoSizing单元格。
我可以在单元初始化的代码中指定约束:
func configureCell() {
snp.makeConstraints { (make) in
make.width.equalToSuperview()
}
}
但是,由于单元格尚未添加到collectionView
,应用程序崩溃。
问题
在cell
生命周期的哪个阶段,可以添加一个具有cell
width
的约束?
是否存在制作cell
的默认方式 宽度
equal to the
宽度of the
的CollectionView without accessing an instance of
UIScreen or
UIWindow`?
编辑问题不重复,因为它不是关于如何使用AutoSizing单元格功能,而是在单元生命周期的哪个阶段应用约束以在使用AutoLayout 时实现所需的结果。
要实现自我调整大小的集合视图单元,您需要做两件事:
UICollectionViewFlowLayout
上指定estimatedItemSize
preferredLayoutAttributesFitting(_:)
UICollectionViewFlowLayout
上指定estimatedItemSize
此属性的默认值为CGSizeZero。 将其设置为任何其他值会导致集合视图使用单元格的preferredLayoutAttributesFitting(_ :)方法查询每个单元格的实际大小。 如果所有单元格的高度相同,请使用itemSize属性而不是此属性来指定单元格大小。
这只是一个用于计算滚动视图内容大小的估计值 ,将其设置为合理的值。
let collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewFlowLayout.estimatedItemSize = CGSize(width: collectionView.frame.width, height: 100)
UICollectionViewCell
子类上实现preferredLayoutAttributesFitting(_:)
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
}
您需要实现sizeForItemAt:来计算大小。
如果你的细胞高度可变,我们也使用了“上浆细胞”。 例如:
class MyFancyCell: UICollectionViewCell {
class func cellSize(_ content: SomeContent, withWidth width: CGFloat) -> CGSize {
sizingCell.content = content
sizingCell.updateCellLayout(width)
return sizingCell.systemLayoutSizeFitting(UILayoutFittingExpandedSize)
}
fileprivate static let sizingCell = Bundle.main.loadNibNamed("ContentCell", owner: nil, options: nil)!.first as! ContentCell
func updateCellLayout(width: CGFloat) {
//Set constraints and calculate size
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.