首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UICollectionView 自定義佈局:實現不規則網格排列

     編輯:程式設計綜合問答

需求

預設 UICollectionViewFlowLayout 為規則網格,需實現自訂行列數(如第一行 5 個、第二行 5 個、第三行 2 個)。

解決方案:繼承 UICollectionViewLayout

  1. 建立 CustomLayout : UICollectionViewLayout
  2. 實現核心方法:
    • prepareLayout:計算所有 UICollectionViewLayoutAttributes
    • layoutAttributesForElementsInRect::回傳可見區域屬性
    • collectionViewContentSize:回傳總內容尺寸
  3. 在 Storyboard/XIB 中將 Collection View 的 Layout 設為 Custom,Class 指定 CustomLayout

關鍵代碼骨架

@interface CustomLayout : UICollectionViewLayout
@end

@implementation CustomLayout
- (void)prepareLayout {
    [super prepareLayout];
    NSMutableArray *attributes = [NSMutableArray array];
    // 根據資料源計算每個 cell 的 frame
    for (NSInteger i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        NSIndexPath *ip = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:ip];
        attr.frame = [self frameForItemAtIndex:i]; // 自訂計算邏輯
        [attributes addObject:attr];
    }
    self.cachedAttributes = attributes;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    return [self.cachedAttributes filteredArrayUsingPredicate:
        [NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *bindings) {
            return CGRectIntersectsRect(rect, ((UICollectionViewLayoutAttributes *)obj).frame);
        }]];
}

- (CGSize)collectionViewContentSize {
    // 返回總高寬
}
@end

參考資源

Apple 官方指南:Creating Custom Layouts

替代方案

若僅需不等寬/高但仍為網格,使用 UICollectionViewDelegateFlowLayout 實現 sizeForItemAtIndexPath 即可,無需完整自定義 Layout。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved