預設 UICollectionViewFlowLayout 為規則網格,需實現自訂行列數(如第一行 5 個、第二行 5 個、第三行 2 個)。
CustomLayout : UICollectionViewLayoutprepareLayout:計算所有 UICollectionViewLayoutAttributeslayoutAttributesForElementsInRect::回傳可見區域屬性collectionViewContentSize:回傳總內容尺寸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。