天天看點

UICollection要點

一、UICollectionView 要點

  • UICollectionLayout

    布局方法的執行順序
  • UICollectionLayout

    實作自定義布局要點
  • UICollect這裡是清單文本ionViewLayoutAttributes

    實作自定義布局屬性要點
  • 重新計算布局屬性
  • 自動對齊到網格

1、UICollectionView 構成

  • Cells
  • Supplementary Views 追加視圖(類似Header 或則 Footer)
  • Decoration Views 裝飾視圖(用作背景展示)

2、布局方法的執行順序

  1. prepareLayout()

  2. -(CGSize)collectionViewContentSize

  3. -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

3、自定義UICollectionLayout實作自定義布局

主要繼承

UICollectionLayout

以下方法,實作布局自定義。
  • -(void)prepareLayout

    開始布局前,調用的方法。可以用來一次把所有的布局屬性放到一個NSArray中。
  • -(CGSize)collectionViewContentSize

    傳回CollectionView的内容尺寸
  • -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

    1. 傳回rect中的所有元素的布局屬性
    2. 傳回的是包含

      UICollectionViewLayoutAttributes

      的NSArray
    3. UICollectionViewLayoutAttributes

      可以是

      Cell

      追加視圖

      裝飾視圖

    4. 不要傳回所有的屬性,隻顯示Rect相交的屬性。節省性能。
  • -(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds

    YES : 邊界發生變化,重新整理布局。

    不要直接傳回YES,判斷UICollectionView的frame改變時再傳回YES。

  • -(UICollectionViewLayoutAttributes _)layoutAttributesForItemAtIndexPath:(NSIndexPath _)indexPath

    傳回對應于indexPath的位置的Cell的布局屬性
  • -(UICollectionViewLayoutAttributes _)layoutAttributesForSupplementaryViewOfKind:(NSString _)kind atIndexPath:(NSIndexPath *)indexPath

    傳回對應于indexPath的位置的追加視圖的布局屬性
  • -(UICollectionViewLayoutAttributes * )layoutAttributesForDecorationViewOfKind:(NSString_)decorationViewKind atIndexPath:(NSIndexPath _)indexPath

    傳回對應于indexPath的位置的裝飾視圖的布局屬性

4、自定義

UICollectionViewLayoutAttributes

主要用來布局cell、追加視圖、裝飾視圖裡面的指定子元素。
  • 實作NSCopying協定?
  • 實作

    -(BOOL)isEqual:(id)object

    父類方法?
  • 在cell、追加視圖、裝飾視圖中,實作

    -(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes

    方法,具體布局指定元素。
  • 在Layout類中實作以下方法?
    • +(Class)layoutAttributesClass

> > ```

這裡輸入代碼

* `invalidateLayout`:執行布局方法,從`-(void)prepareLayout`方法開始重新計算布局。

### 6、切換布局

> 注意:切換的2個布局必須已經實作了 `-(UICollectionViewLayoutAttributes _)layoutAttributesForItemAtIndexPath:(NSIndexPath _)indexPath`方法。否則會報錯。

* `setCollectionViewLayout:animated:`

### 7、動畫效果


* `initialLayoutAttributesForAppearingItemAtIndexPath:`
* `initialLayoutAttributesForAppearingSupplementaryElementOfKind:atIndexPath:`
* `initialLayoutAttributesForAppearingDecorationElementOfKind:atIndexPath:`
* `finalLayoutAttributesForDisappearingItemAtIndexPath:`
* `finalLayoutAttributesForDisappearingSupplementaryElementOfKind:atIndexPath:`
* `finalLayoutAttributesForDisappearingDecorationElementOfKind:atIndexPath:`


> ### 8、DEMO與參考

* [貓神的UICollection手冊](https://onevcat.com/2012/08/advanced-collection-view/)
* [自定義CollectionView布局 @ObjC中國](https://objccn.io/issue-3-3/)
* [raywender自定義CollectoionView布局](https://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest)
           

轉載于:https://my.oschina.net/u/2385300/blog/826225