在底部启动UICollectionView

Nic*_*mas 10 cocoa-touch uikit ios uicollectionview ios7

在iOS 7中,给定一个UICollectionView,你如何在底部启动它?想想iOS消息应用程序,当视图变得可见时,它始终从底部开始(最新消息).

cod*_*ran 6

@awolf您的解决方案很好!但是不能与自动布局一起使用。

您应该先调用[self.view layoutIfNeeded]!完整的解决方案是:

- (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];
    }
}
Run Code Online (Sandbox Code Playgroud)


awo*_*olf 4

问题是,如果您尝试在 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];
    }
}
Run Code Online (Sandbox Code Playgroud)