Reputation: 2832
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.
Upvotes: 3
Views: 1168
Reputation: 536
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
}
}
Upvotes: 2