Launch UICollectionView at the bottom

In iOS 7, given the UICollectionView, how do you start it down? Think of the iOS Messages app, where when a view becomes visible, it always starts at the bottom (last message).

+8
ios cocoa-touch uikit ios7 uicollectionview
source share
6 answers

The problem is that if you try to set the contentOffset of your collection view to viewWillAppear, the collection view has not yet displayed its elements. Therefore, self.collectionView.contentSize is still {0,0}. The solution is to ask the collection view layout for the size of the content.

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

The complete solution looks like this:

- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; CGSize contentSize = [self.collectionView.collectionViewLayout collectionViewContentSize]; if (contentSize.height > self.collectionView.bounds.size.height) { CGPoint targetContentOffset = CGPointMake(0.0f, contentSize.height - self.collectionView.bounds.size.height); [self.collectionView setContentOffset:targetContentOffset]; } } 
+2
source share

@awolf Your decision is good! But do not work well with startup.

You should call [self.view layoutIfNeeded] first! Complete solution:

 - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // ---- autolayout ---- [self.view layoutIfNeeded]; CGSize contentSize = [self.collectionView.collectionViewLayout collectionViewContentSize]; if (contentSize.height > self.collectionView.bounds.size.height) { CGPoint targetContentOffset = CGPointMake(0.0f, contentSize.height - self.collectionView.bounds.size.height); [self.collectionView setContentOffset:targetContentOffset]; } } 
+2
source share
 yourCollectionView.contentOffset = CGPointMake(0, yourCollectionView.contentSize.height - yourCollectionView.bounds.size.height); 

But remember to do this only when your contentSize.height > bounds.size.height .

+1
source share

This works for me, and I think this is a modern way.

 override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.collectionView!.scrollToItemAtIndexPath(indexForTheLast, atScrollPosition: UICollectionViewScrollPosition.Bottom, animated: false) } 
+1
source share

Assuming you know how many items are in your collection view, you can use

scrollToItemAtIndexPath:atScrollPosition:animated:

Apple docs

0
source share

it works great for me (self-timer)

  • Calculate the size of the contents of a ScrollView using collectionViewFlowLayout and cellSize
  • collectionView.contentSize = calculateContentSize
  • collectionView.scrollToItemAtIndexPath (whichYouWantToScrollIndexPath, atScrollPosition: ...)
0
source share

All Articles