Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set items in collection view go bottom-to-top with swift

I'm making a collection view with fixed height and width and horizontal scroll direction.

At the start I will have 1 cell and I want it in the right side of the collection view instead of the left and when more cells are coming I want them to stack in the right side of the previous cell like 1 - 2 - 3.

I searched for an answer but all similar questions were for objective c.

Any thoughts how could I do this with swift?

Thanks in advance.

like image 612
mike vorisis Avatar asked Feb 02 '26 02:02

mike vorisis


1 Answers

The problem is that if you try to set the contentOffset of your collection view in viewWillAppear, the collection view hasn't rendered its items yet. Therefore self.collectionView.contentSize is still {0,0}. The solution is to ask the collection view's layout for the content size.

Additionally, you'll want to make sure that you only set the contentOffset when the contentSize is taller than the bounds of your collection view.

 func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

 let contentSize: CGSize? = collectionView?.collectionViewLayout.collectionViewContentSize
    if contentSize?.height > collectionView?.bounds.size.height {

        let targetContentOffset = CGPoint(x: 0.0, y: (contentSize?.height)! - (collectionView?.bounds.size.height)!)
        collectionView?.contentOffset = targetContentOffset
      }

 }
like image 126
Quiet Islet Avatar answered Feb 04 '26 14:02

Quiet Islet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!