一、UICollectionView 要點
-
布局方法的執行順序UICollectionLayout
-
實作自定義布局要點UICollectionLayout
-
實作自定義布局屬性要點UICollect這裡是清單文本ionViewLayoutAttributes
- 重新計算布局屬性
- 自動對齊到網格
1、UICollectionView 構成
- Cells
- Supplementary Views 追加視圖(類似Header 或則 Footer)
- Decoration Views 裝飾視圖(用作背景展示)
2、布局方法的執行順序
-
prepareLayout()
-
-(CGSize)collectionViewContentSize
-
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
3、自定義UICollectionLayout實作自定義布局
主要繼承 UICollectionLayout
以下方法,實作布局自定義。
-
-(void)prepareLayout
開始布局前,調用的方法。可以用來一次把所有的布局屬性放到一個NSArray中。
-
-(CGSize)collectionViewContentSize
傳回CollectionView的内容尺寸
-
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
- 傳回rect中的所有元素的布局屬性
- 傳回的是包含
的NSArrayUICollectionViewLayoutAttributes
-
可以是UICollectionViewLayoutAttributes
、Cell
、追加視圖
裝飾視圖
- 不要傳回所有的屬性,隻顯示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
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