2014-02-15 39 views
8

在iOS 7中,給定一個UICollectionView,你如何在底部啓動它?想想iOS消息應用程序,當視圖變得可見時,它總是從底部開始(最近的消息)。在底部啓動UICollectionView

回答

2

問題是,如果您嘗試在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]; 
    } 
} 
+0

不適用於自動佈局。 – Chris

0

假設你知道有多少項目是在您的收藏視圖,您可以使用

scrollToItemAtIndexPath:atScrollPosition:animated:

Apple Docs

1
yourCollectionView.contentOffset = CGPointMake(0, yourCollectionView.contentSize.height - yourCollectionView.bounds.size.height); 

但要記住做只有這個時候你contentSize.height>bounds.size.height

1

這對我的作品,我認爲這是一個現代的方式。

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

@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]; 
    } 
} 
0

它完美對我來說(自動版式)使用collectionViewFlowLayout和CELLSIZE

  • collectionView.contentSize = calculatedContentSize
  • collectionView.scrollToItemAtIndexPath(whichYouWantToScrollIndexPath

    1. 計算滾動型的內容大小,atScrollPosition:...)