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.
问题
在cell生命周期的哪个阶段,可以用cell's width?添加约束?
有没有作出任何默认方式cell的widthequal to the
宽of the的CollectionView without accessing an instance of
UIScreen orUIWindow`?
编辑 问题不重复,因为它不是关于如何使用AutoSizing单元格功能,而是在单元生命周期的哪个阶段应用约束以在使用AutoLayout 时实现所需的结果.
Oli*_*son 33
要实现自我调整大小的集合视图单元,您需要做两件事:
estimatedItemSize有关UICollectionViewFlowLayoutpreferredLayoutAttributesFitting(_:)在您的手机上实施estimatedItemSize有关UICollectionViewFlowLayout此属性的默认值为CGSizeZero.将其设置为任何其他值会导致集合视图使用单元格的preferredLayoutAttributesFitting(_ :)方法查询每个单元格的实际大小.如果所有单元格的高度相同,请使用itemSize属性而不是此属性来指定单元格大小.
这只是一个用于计算滚动视图内容大小的估计值,将其设置为合理的值.
let collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewFlowLayout.estimatedItemSize = CGSize(width: collectionView.frame.width, height: 100)
Run Code Online (Sandbox Code Playgroud)
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)
| 归档时间: |
|
| 查看次数: |
5778 次 |
| 最近记录: |