在iOS 7中,给定UICollectionView,如何在底部启动它?想想iOS消息应用程序,当视图变得可见时,它总是从底部开始(最近的消息)。
@awolf你的解决方案很好!但不能很好地与自动布局配合使用。
你应该先调用[self.view layoutIfNeed]!完整的解决方案是:
- (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];
}
}
问题是,如果您尝试在 viewWillAppear 中设置集合视图的 contentOffset ,则集合视图尚未呈现其项目。因此,self.collectionView.contentSize 仍然是 {0,0}。解决方案是询问集合视图的布局以了解内容大小。
此外,您需要确保仅在 contentSize 高于集合视图的边界时设置 contentOffset。
完整的解决方案如下所示:
- (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];
}
}
这对我有用,我认为这是一种现代方式。
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.collectionView!.scrollToItemAtIndexPath(indexForTheLast, atScrollPosition: UICollectionViewScrollPosition.Bottom, animated: false)
}
yourCollectionView.contentOffset = CGPointMake(0, yourCollectionView.contentSize.height - yourCollectionView.bounds.size.height);
但请记住,只有在您的contentSize.height
> bounds.size.height
时才这样做。
假设您知道集合视图中有多少项
可以使用 scrollToItemAtIndexPath:atScrollPosition:animated:
苹果文档
它非常适合我(自动布局)
- 使用 collectionViewFlowLayout 和 cellSize 计算 ScrollView 的内容大小
- 集合视图.内容大小 = 计算内容大小
- collectionView.scrollToItemAtIndexPath(whichYouWantToScrollIndexPath, atScrollPosition: ...)
viewWillLayoutSubviews
scrollToItemAtIndexPath:atScrollPosition:animated:
中添加,以便集合视图将立即加载到底部