I have a custom UICollectionViewFlowLayout
subclass which displays all cells on top of each other (so only the topmost cell is actually visible to the user). I suppose since all views are in frame, the UICollectionView
renders all cells even though only one is actually visible to the user.
Is there any way I can influence the number of cells the UICollectionView
renders? I'd prefer to only render the first two or three cells.
class UICollectionViewStackLayout: UICollectionViewFlowLayout {
override init() {
super.init()
self.scrollDirection = .vertical
self.minimumInteritemSpacing = 0
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard
let attributes = super.layoutAttributesForElements(in: rect),
let collectionView = self.collectionView
else {
return nil
}
for attribute in attributes {
attribute.zIndex = Int.max - attribute.indexPath.item // First item on top
attribute.center = collectionView.center
}
return attributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return UICollectionViewLayoutAttributes(forCellWith: indexPath)
}
}