Nick Stamas Nick Stamas - 1 year ago 101
iOS Question

Start UICollectionView at bottom

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

Answer Source

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.

A full solution looks like:

- (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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download