CollectionView scroll to top
Solution 1
Add this line after reloading the collection view.
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
Edit:
Just want to add one more point here is if collectionView datasource has ZERO elements or it is nil
then above code will not work and probably crash your app.
Write condition to check that datasource is available or not!
if (self.dataArray.count > 0) {
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
}
Where, dataArray
is your datasource.
Solution 2
in swift 3: after reloadData()
self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: true)
Solution 3
Its work fine......
collectionView.setContentOffset(.zero, animated: false)
Solution 4
Add this piece of code after reloading the collection view:
swift
yourCollectionView.setContentOffset(CGPoint.zero, animated: true)
objective-c
[yourCollectionView setContentOffset:CGPointZero animated:YES];
Solution 5
Swift 4 Swift 5
Actually, it's work just do
collectionView.setContentOffset(.zero, animated: false)
But, if in case your CollectionView implement .contentInset
or outer margin, let's say margin top & bottom is set 16
, this code will actually back to the top.
collectionView.setContentOffset(CGPoint(x: 0, y: -16), animated: true)
Related videos on Youtube
Comments
-
KAR about 3 years
I have one CollectionViewController and have 10 cells in it.
But when I run the app it displays the cell at bottom, but I want to display it from top cell at viewDidLoad.
I tried many things but it didn't work.
How to fix it?
-
Pooja Srivastava over 7 yearsplease share your code..
-
KAR over 7 yearsI am using this, cocoapods.org/pods/SFFocusViewLayout. @PoojaSrivastava
-
Jitendra Modi over 7 years@KAR Please share some code and screenshot of what type of collectionviewcell you want to get? Like what is problem ?
-
User511 over 7 yearsAre you working in Swift?
-
KAR over 7 yearsNo, objective c. @Aisha
-
-
KAR over 7 yearswhere to add this line? @Monika patel
-
Monika Patel over 7 years@KAR : Add this line after
[self.collectionview reloaddata];
-
Monika Patel over 7 years@KAR : Please up vote my answer. If my answer is useful to you
-
KAR over 7 yearsPlease up vote the question so it will helpful to others. @Monika Patel
-
KAR over 7 yearsno. view works fine before I rotate it 180. So after that it shows cell from bottom. I flip the view for change animation effect to opposite. @Monika Patel
-
KAR over 7 yearsIf you are feeling that this question will be helpful to others than upvote the question. @Aisha
-
Ahmadreza over 5 yearsWorks with Swift 4+ too