UICollectionViewLayout佈局詳解

簡介

Supplementary Views 追加視圖 (相似Header或者FooterDecoration Views 裝飾視圖 (用做背景展現)
複製代碼

對於cell的樣式和組織方式,因爲collectionView比tableView要複雜得多,所以沒有按照相似於tableView的style的方式來定義,而是專門使用了一個類來對collectionView的佈局和行爲進行描述,這就是UICollectionViewLayoutobjective-c

而咱們主要講UICollectionViewLayout,由於這不只是collectionView和tableView的最重要求的區別,也是整個UICollectionView的精髓所在。swift

UICollectionViewLayoutAttributes

@property (nonatomic) CGRect frame
@property (nonatomic) CGPoint center
@property (nonatomic) CGSize size
@property (nonatomic) CATransform3D transform3D
@property (nonatomic) CGFloat alpha
@property (nonatomic) NSInteger zIndex
@property (nonatomic, getter=isHidden) BOOL hidden
複製代碼

能夠看到,UICollectionViewLayoutAttributes的實例中包含了諸如邊框,中心點,大小,形狀,透明度,層次關係和是否隱藏等信息。數組

  1. 一個cell對應一個UICollectionViewLayoutAttributes對象
  2. UICollectionViewLayoutAttributes對象決定了cell的擺設位置(frame)

自定義UICollectionViewLayout

UICollectionViewLayout的功能爲向UICollectionView提供佈局信息,不只包括cell的佈局信息,也包括追加視圖和裝飾視圖的佈局信息。實現一個自定義layout的常規作法是繼承UICollectionViewLayout類,而後重載下列方法:oop

-(void)prepareLayout
prepare方法被自動調用,以保證layout實例的正確。

-(CGSize)collectionViewContentSize
返回collectionView的內容的尺寸

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
 1. 返回rect中的全部的元素的佈局屬性
 2. 返回的是包含UICollectionViewLayoutAttributes的NSArray
 3. UICollectionViewLayoutAttributes能夠是cell,追加視圖或裝飾視圖的信息,經過不一樣的UICollectionViewLayoutAttributes初始化方法能夠獲得不一樣類型的UICollectionViewLayoutAttributes:
  1)layoutAttributesForCellWithIndexPath:
  2)layoutAttributesForSupplementaryViewOfKind:withIndexPath:
  3)layoutAttributesForDecorationViewOfKind:withIndexPath:

-(UICollectionViewLayoutAttributes )layoutAttributesForItemAtIndexPath:(NSIndexPath )indexPath
返回對應於indexPath的位置的cell的佈局屬性

-(UICollectionViewLayoutAttributes )layoutAttributesForSupplementaryViewOfKind:(NSString )kind atIndexPath:(NSIndexPath *)indexPath
返回對應於indexPath的位置的追加視圖的佈局屬性,若是沒有追加視圖可不重載

-(UICollectionViewLayoutAttributes * )layoutAttributesForDecorationViewOfKind:(NSString)decorationViewKind atIndexPath:(NSIndexPath )indexPath
返回對應於indexPath的位置的裝飾視圖的佈局屬性,若是沒有裝飾視圖可不重載

-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
當邊界發生改變時,是否應該刷新佈局。若是YES則在邊界變化(通常是scroll到其餘地方)時,將從新計算須要的佈局信息。
調用順序
複製代碼

調用順序

1)-(void)prepareLayout  
  a. collection view 只會在第一次layout的時候調用一次`-prepareLayout`,做爲第一次通知layout實例對象的消息
  b. collection view 會在 layout 對象 invalidated 以後而且requerying以前再次調用
  c. 繼承自UICollectionViewLayout都須要重寫這個方法,通常都是在這個方法裏面準備好`layoutAttributesForElements(in:)`這個方法要使用到的`UICollectionViewLayoutAttributes`數組。
  
2)  -(CGSize) collectionViewContentSize 
  a. 肯定collectionView的全部內容的尺寸
  b. 每一次移動collection view時都會調用這個方法,而且這個方法會被調用屢次

3)-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
  初始的layout的外觀將由該方法返回的UICollectionViewLayoutAttributes來決定。

4)在須要更新layout時,須要給當前layout發送 
     1)-invalidateLayout, 該消息會當即返回,而且預定在下一個loop的時候刷新當前layout
     2)-prepareLayout,
     3)依次再調用-collectionViewContentSize和-layoutAttributesForElementsInRect來生成更新後的佈局。
複製代碼
相關文章
相關標籤/搜索