Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CollectionView scroll to top

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?

like image 888
KAR Avatar asked Sep 14 '16 12:09

KAR


3 Answers

in swift 3: after reloadData()

  self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: true)
like image 105
Lam Nguyen Avatar answered Nov 14 '22 01:11

Lam Nguyen


Its work fine......

collectionView.setContentOffset(.zero, animated: false)
like image 17
Srinivasan_iOS Avatar answered Nov 14 '22 02:11

Srinivasan_iOS


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.

like image 16
User511 Avatar answered Nov 14 '22 03:11

User511