Reputation: 1871
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).
Upvotes: 13
Views: 8392
Reputation: 61
added in scrollToItemAtIndexPath:atScrollPosition:animated:
in viewWillLayoutSubviews
so that the collectionView will be loaded instantly at the bottom
Upvotes: 0
Reputation: 131
it works perfectly for me (autolayout)
Upvotes: 0
Reputation: 423
@awolf Your solution is good! But do not work well with autolayout.
You should call [self.view layoutIfNeeded] first! Full solution is:
- (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];
}
}
Upvotes: 7
Reputation: 8875
This works for me and i think it is a modern way.
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.collectionView!.scrollToItemAtIndexPath(indexForTheLast, atScrollPosition: UICollectionViewScrollPosition.Bottom, animated: false)
}
Upvotes: 3
Reputation: 1972
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];
}
}
Upvotes: 4
Reputation: 4271
yourCollectionView.contentOffset = CGPointMake(0, yourCollectionView.contentSize.height - yourCollectionView.bounds.size.height);
But remember to do this only when your contentSize.height
> bounds.size.height
.
Upvotes: 1
Reputation: 8511
Assuming that you know how many items are in your collection view you can use
scrollToItemAtIndexPath:atScrollPosition:animated:
Upvotes: 0