I'm using AutoSizing cells with Autolayout and UICollectionView.
I can specify constraints in code on cell initialization:
func configureCell() {
snp.makeConstraints { (make) in
make.width.equalToSuperview()
}
}
However, the app crashes as the cell hasn't been yet added to the collectionView
.
Questions
At which stage of the
cell
's lifecycle it is possible to add a constraint withcell
'swidth
?Is there any default way of making a
cell
'swidth
equal to the
widthof the
collectionViewwithout accessing an instance of
UIScreenor
UIWindow`?
Edit The question is not duplicate, as it is not about how to use the AutoSizing cells feature, but at which stage of the cell lifecycle to apply constraints to achieve the desired result when working with AutoLayout.
To implement self-sizing collection view cells you need to do two things:
estimatedItemSize
onUICollectionViewFlowLayout
preferredLayoutAttributesFitting(_:)
on your cell1. Specifying
estimatedItemSize
onUICollectionViewFlowLayout
This is just an estimate which is used to calculate the content size of the scroll view, set it to something sensible.
2. Implement
preferredLayoutAttributesFitting(_:)
on yourUICollectionViewCell
subclassYou'll need to implement sizeForItemAt: to calculate the size.
We've also used a "sizing cell" if your cells have variable height. Eg: