您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

布局萬花筒:自定義 UICollectionViewLayout 實現任意排列

編輯:iOS 開發基礎

UICollectionView 從 iOS 6 開始提供,它和 UITableView 共享同一套 API 設計思路:都基於 dataSource 與 delegate,都繼承自 UIScrollView。但它比 tableView 走得更遠——它把子視圖的位置、大小、transform 全部委託給了一個獨立的布局對象:UICollectionViewLayout。這是個抽象類,繼承它你就能實現任何想要的排列;系統也給了一份開箱即用的實現:UICollectionViewFlowLayout。在我看來,沒有哪種排列是 UICollectionViewLayout 做不到的,如果有,那就自定義一個。

UITableView 只能豎向滑動,cell 寬度默認與 tableView 一致,排列順序也只能挨次往下。UICollectionView 提供了更多可能:豎向、橫向都行,cell 的位置與尺寸完全由你決定。所以下次遇到橫向滑動的需求,先別急著掏 UIScrollView,可以想想 UICollectionView 是否能勝任——額外的好處是,cell 復用問題系統已經幫你解決了。

本文講解如何自定義 UICollectionViewLayout 來實現任意布局,默認你已經會用系統的 UICollectionViewFlowLayout 做標準 Grid View。

1. UICollectionViewFlowLayout

系統提供的 UICollectionViewFlowLayout 能實現 Grid View 樣式,也就是一格一格挨次排列。大多數場景下它就夠用了,我們只需要確定幾個參數:

NS_CLASS_AVAILABLE_IOS(6_0) @interface UICollectionViewFlowLayout : UICollectionViewLayout @property (nonatomic) CGFloat minimumLineSpacing; @property (nonatomic) CGFloat minimumInteritemSpacing; @property (nonatomic) CGSize itemSize; @property (nonatomic) CGSize estimatedItemSize NS_AVAILABLE_IOS(8_0); // defaults to CGSizeZero - setting a non-zero size enables cells that self-size via -preferredLayoutAttributesFittingAttributes: @property (nonatomic) UICollectionViewScrollDirection scrollDirection; // default is UICollectionViewScrollDirectionVertical @property (nonatomic) CGSize headerReferenceSize; @property (nonatomic) CGSize footerReferenceSize; @property (nonatomic) UIEdgeInsets sectionInset; // Set these properties to YES to get headers that pin to the top of the screen and footers that pin to the bottom while scrolling (similar to UITableView). @property (nonatomic) BOOL sectionHeadersPinToVisibleBounds NS_AVAILABLE_IOS(9_0); @property (nonatomic) BOOL sectionFootersPinToVisibleBounds NS_AVAILABLE_IOS(9_0); @end

Grid View 樣式如下:

如果這種排列滿足不了需求,就該自定義 Layout 了。

2. UICollectionViewLayout 與 FlowLayout 的取捨

FlowLayout 繼承自 UICollectionViewLayout。用它的好處是省心:只要給出 cell 大小以及行間距、列間距,它會自己算好每個 cell 的位置和整個 collectionView 的 contentSize。代價是它只能提供單一方向的滑動——你的子類繼承自 FlowLayout,布局就只能是水平或豎直其一。

需要更自由的布局時,就只能直接繼承 UICollectionViewLayout。它是抽象類,不能直接使用。

3. 自定義布局需要實現的方法

官方文檔列出了需要實現的方法:

這六個方法並非都得自己寫,按需選擇即可。

collectionViewContentSize

UICollectionView 繼承自 UIScrollView,而 contentSize 是 UIScrollView 的關鍵參數:這個值不對,內容就沒法完整滾動展示。collectionViewContentSize 就是為了提供它。可以把 collectionView 想成一塊畫板,這個方法規定了畫板尺寸。

如果你繼承自 FlowLayout,且 cell 的大小位置都由 FlowLayout 的參數決定、沒有在自定義過程中随意改動,那麼 contentSize 可以不重寫,系統會自己算。若繼承自 UICollectionViewLayout,就得根據自己的布局返回合適的 CGSize。

layoutAttributesForElementsInRect

參數是 collectionView 當前的 bounds,也就是可見區域;返回值是 UICollectionViewLayoutAttributes 對象組成的數組。可見區域內包含 cell、supplementary view、decoration view(統稱 cell,因為它們都是 collectionView 的子視圖),它們的位置、大小都由對應的 LayoutAttributes 控制。默認情況下 LayoutAttributes 包含 indexPath、frame、center、size、transform3D、alpha 和 hidden。想控制更多屬性,可以自定義一個 UICollectionViewLayoutAttributes 子類,把需要的字段加上去。

LayoutAttributes 通過 indexPath 與 cell 關聯:collectionView 展示 cell 時,就是靠這些屬性對象拿布局信息。所以這個方法的返回值,本質上是傳入的矩形區域內所有 cell 對應的 LayoutAttributes。

常見的獲取步驟:

  • 如果你繼承自 FlowLayout,且 itemSize、行間距、列間距都設好了,直接調 [super layoutAttributesForElementsInRect:rect] 就能拿到可見區域內的布局屬性;否則進入下一步。

  • 建一個數組用來存放結果。

  • 從數據源取出要展示的數據,按你的布局規則算出哪些 indexPath 落在當前可見區域內——用 CGRectIntersectsRect 判斷兩個矩形是否相交即可。然後循環調用 layoutAttributesForItemAtIndexPath: 確定每個屬性對象的 frame 等數據。若當前區域內還有 supplementary view 或 decoration view,還需要調用 layoutAttributesForSupplementaryViewOfKind:atIndexPath: 或 layoutAttributesForDecorationViewOfKind:atIndexPath:,最後一起裝進數組返回。

補充一點:有些布局(比如瀑布流)可以在 prepareLayout 階段就依據數據源把所有布局屬性預先算好,那麼這個方法裡只需要篩出 frame 與可見區域有交集的那些返回。

layoutAttributesFor…IndexPath

這裡是省略寫法,實際有三個類似的接口:

  • layoutAttributesForItemAtIndexPath:

  • layoutAttributesForSupplementaryViewOfKind:atIndexPath:

  • layoutAttributesForDecorationViewOfKind:atIndexPath:

分別為 cell、supplementaryView、decorationView 返回布局屬性。它們並非必須實現——如果你能通過別的途徑拿到對應 indexPath 的屬性,就沒必要非得寫這幾個。

以 layoutAttributesForItemAtIndexPath: 為例:用 +[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:] 拿到一個屬性對象,再訪問數據源算出該 indexPath 的 frame 等信息賦值給它即可。

shouldInvalidateLayoutForBoundsChange

用來告訴 collectionView:bounds 變化時是否需要重新計算布局,典型場景是橫豎屏旋轉。常見寫法:

  - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {     CGRect oldBounds = self.collectionView.bounds;     if (CGRectGetWidth(newBounds) != CGRectGetWidth(oldBounds)) {         return YES;     }         return NO; }

要注意的是:如果滑動過程中需要動態改變某些 cell 的布局,這裡就得返回 YES,讓 collectionView 重新計算——因為任何一個 cell 的變化都可能牽動整體布局。

4. 示例一:瀑布流

瀑布流常用於圖片或商品展示,特點是等寬變高:每個 cell 都放進當前最矮的那一列。效果如下:

這裡行間距、列間距都取 10,固定 3 列。系統的 FlowLayout 顯然做不到——它默認是整齊對齊的網格。所以我們新建一個繼承自 UICollectionViewFlowLayout 的類。

prepareLayout

先說說 prepareLayout:它在 collectionView 布局之前被調用;調用 reloadData、invalidateLayout,或者 shouldInvalidateLayoutForBoundsChange 返回 YES 時,它也會被調用。所以這是提前做布局計算的最佳位置。

瀑布流可以在這裡依據數據源把所有布局屬性算好並緩存:

  - (void)prepareLayout {     [super prepareLayout];     //記錄布局需要的contentSize的高度     self.contentHeight = 0;     //columnHeights數組會記錄各列的當前布局高度     [self.columnHeights removeAllObjects];         //默認高度是sectionEdge.top     for (NSInteger i = 0; i < self.columnCount; i++) {         [self.columnHeights addObject:@(self.edgeInsets.top)];     }     //清除之前所以的布局屬性數據     [self.attrsArray removeAllObjects];     //通過數據源拿到需要展示的cell數量     NSInteger count = [self.collectionView numberOfItemsInSection:0];     //開始創建每一個cell對應的布局屬性     for (NSInteger index = 0; index < count; index++) {         //創建indexPath         NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];         //獲取cell布局屬性,在layoutAttributesForItemAtIndexPath裡面計算具體的布局信息         UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];         [self.attrsArray addObject:attrs];     } }

而在 layoutAttributesForItemAtIndexPath 裡,按 indexPath 取出數據源裡對應位置的高度,在等寬前提下算出 cell 高度,再從記錄各列當前高度的 columnHeights 數組中找出最矮的一列,由此確定 origin,就得到了完整的 frame。隨後更新 columnHeights,並讓 contentHeight 等於列高度數組中的最大值。

  -(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {     //獲取一個UICollectionViewLayoutAttributes對象     UICollectionViewLayoutAttributes *attrs = [super layoutAttributesForItemAtIndexPath:indexPath];     //列數是3,布局屬性的寬度是固定的     CGFloat collectionViewW = self.collectionView.frame.size.width;     CGFloat width = (collectionViewW - self.edgeInsets.left - self.edgeInsets.right - (self.columnCount - 1) * self.columnMargin) / self.columnCount;     CGFloat height = 通過數據源以及寬度信息,獲取對應位置的布局屬性高度;     //找到數組內目前高度最小的那一列     NSInteger destColumn = 0;     CGFloat minColumnHeight = [self.columnHeights[0] doubleValue];     for (NSInteger index = 1; index < self.columnCount; index++) {           CGFloat columnHeight = [self.columnHeights[index] doubleValue];         if (minColumnHeight > columnHeight) {             minColumnHeight = columnHeight;             destColumn = index;             break;         }     }     //根據列信息,計算出origin的x     CGFloat x = self.edgeInsets.left + destColumn * (width +self.columnMargin);     CGFloat y = minColumnHeight;     if (y != self.edgeInsets.top) {//不是第一行就加上行間距         y += self.rowMargin;     }     //得到布局屬性的frame信息     attrs.frame = CGRectMake(x, y, width, height);     //更新最短那列的高度     self.columnHeights[destColumn] = @(CGRectGetMaxY(attrs.frame));     //更新記錄展示布局所需的高度     CGFloat columnHeight = [self.columnHeights[destColumn] doubleValue];     if (self.contentHeight < columnHeight) {         self.contentHeight = columnHeight;     }          return attrs; }

滑動時 cell 會不斷復用,系統反覆調用 layoutAttributesForElementsInRect 索取可見區域的布局屬性。由於前面已經全部緩存,這裡只需篩出與 rect 相交的那些:

  -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {     NSMutableArray *rArray = [NSMutableArray array];     for (UICollectionViewLayoutAttributes *cacheAttr in _attrsArray) {         if (CGRectIntersectsRect(cacheAttr.frame, rect)) {             [rArray addObject:cacheAttr];         }     }     return rArray; }

最後,因為每個 cell 的高度是我們自己定的,系統無從得知 contentSize,必須在 collectionViewContentSize 裡返回正確的值,否則後面的 cell 滾不到可見區域:

  -(CGSize)collectionViewContentSize {     return CGSizeMake(CGRectGetWidth(self.collectionView.frame), self.contentHeight + self.edgeInsets.bottom); }

至此瀑布流完成。整體並不複雜,最關鍵的就是計算布局屬性的 frame。

5. 示例二:卡片吸頂

效果如下:

可以看到,本該滾出可見區域的 cell 在到達頂部後懸停了下來,並且不斷被後來的 cell 覆蓋。

實現原理很簡單。cell 本身的排列用 FlowLayout 就夠了,我們新建一個繼承自 UICollectionViewFlowLayout 的子類:

只要提供 itemSize 和 minimumLineSpacing 就能搭出未吸頂的版本;把行間距設為負數,就能形成互相疊加的視覺效果。

吸頂效果則是在原布局基礎上加一句判斷:若布局屬性的 frame 已高於頂部 y 值,就把它的 y 釘在頂部。這樣滑到頂部的 cell 都會懸停在那裡。

@implementation CardCollectionViewFlowLayout - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {     //拿到當前可見區域內的布局屬性     NSArray *oldItems = [super layoutAttributesForElementsInRect:rect];     //處理當前可見區域內的布局屬性吸頂     [oldItems enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes *attributes, NSUInteger idx, BOOL *stop) {         [self recomputeCellAttributesFrame:attributes];     }];         return oldItems; } - (void)recomputeCellAttributesFrame:(UICollectionViewLayoutAttributes *)attributes {     //獲取懸停處的y值     CGFloat minY = CGRectGetMinY(self.collectionView.bounds) + self.collectionView.contentInset.top;     //拿到布局屬性應該出現的位置     CGFloat finalY = MAX(minY, attributes.frame.origin.y);         CGPoint origin = attributes.frame.origin;     origin.y = finalY;     attributes.frame = (CGRect){origin, attributes.frame.size};     //根據IndexPath設置zIndex能確立頂部懸停的cell被後來的cell覆蓋的層級關系     attributes.zIndex = attributes.indexPath.row; } - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {     //由於cell在滑動過程中會不斷修改cell的位置,所以需要不斷重新計算所有布局屬性的信息     return YES; } @end

這裡不需要重寫 collectionViewContentSize,因為布局仍基於 FlowLayout,系統會依據 itemSize 等參數自動算出 contentSize。

6. 總結

從兩個例子不難看出:UICollectionView 是一塊畫板,而 UICollectionViewLayout 決定了畫板的尺寸以及內容的組織形態。日常需求裡用好 UICollectionView,往往能起到事半功倍的效果。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved