0

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)
    }
}
Richard N.
  • 87
  • 4
  • 1
    I don't know if it works, but: What about doing `return Array(attributes.sorted(by: { $0.zIndex < $1.zIndex }).prefix(2))` instead of `return attributes`? Not that it's `$0.zIndex < $1.zIndex ` or `$0.zIndex > $1.zIndex`, to test. – Larme Oct 01 '19 at 15:52
  • The layout works fine, my question was about whether I can change the number of cells rendered by the UICollectionView (so I don't render 100 even though the user only ever sees the topmost cell). – Richard N. Oct 02 '19 at 07:36
  • 1
    That's what I'm saying. If you returns only 2 layouts, it should render to cells in the defined `rect`, that what I'm guessing. – Larme Oct 02 '19 at 07:38
  • Aaah of course! Thank you, this works. – Richard N. Oct 02 '19 at 07:49

0 Answers0