瀑布流是電商類 App 展示商品最常見的版型,如下圖。

實作方式大致有三種:
UITableView(少見)UITableView 或 UIScrollView 手刻(工作量大)UICollectionView(主流做法)它與 UITableView 有不少相似之處:都由 data source 提供資料、由 delegate 處理事件、都支援自訂 cell 與重用機制、也都繼承自 UIScrollView 因而具備滾動能力。
差異在於:UICollectionView 必須搭配一個 UICollectionViewLayout(通常是 UICollectionViewFlowLayout)或其子類來決定版面;而我們正是可以繼承 Layout,自行定義滾動方向與 cell 的排列規則。UICollectionViewFlowLayout 就是所謂的流水佈局,也是最常用的一種。
佈局初始化:
- (void)prepareLayout {
// 在此完成佈局初始化
}
尺寸變動時是否重算:
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES; // 預設即為 YES
}
回傳指定矩形區域內所有元素的佈局屬性,以及單一元素的佈局屬性:
- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)
layoutAttributesForElementsInRect:(CGRect)rect {
// 需回傳 rect 區域內所有元素的佈局屬性
}
- (nullable UICollectionViewLayoutAttributes *)
layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
// 回傳 indexPath 位置元素的佈局屬性
}
控制停止滾動時的最終偏移量(常用於「吸附置中」效果):
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
withScrollingVelocity:(CGPoint)velocity {
// 回傳值即為 UICollectionView 最終停留的點
}

此範例的設計:以 UICollectionView 為基礎,實作「橫向伸縮流水」與「圓形排列」兩種自訂版面;點擊 cell 可將其刪除;點擊控制器主視圖則在兩種版面之間切換。
初始化時設定橫向滾動與左右內嵌,讓頭尾留白:
- (void)prepareLayout {
[super prepareLayout];
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width) * 0.5;
self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
核心效果:以 collectionView 中點為基準,離中點越遠的 cell 縮得越小,形成透視般的伸縮感:
- (nullable NSArray<UICollectionViewLayoutAttributes *> *)
layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *array = [super layoutAttributesForElementsInRect:rect];
// 以 contentView 左上角為原點,算出 collectionView 的中點
CGFloat centerX = self.collectionView.contentOffset.x
+ self.collectionView.frame.size.width * 0.5;
for (UICollectionViewLayoutAttributes *attribute in array) {
CGFloat delta = ABS(attribute.center.x - centerX);
CGFloat scale = 1 - delta / self.collectionView.bounds.size.width;
attribute.transform = CGAffineTransformMakeScale(scale, scale);
}
return [array copy];
}
再讓滾動停止時自動吸附,使最接近中點的 cell 精準置中:
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
withScrollingVelocity:(CGPoint)velocity {
CGRect rect;
rect.origin = CGPointMake(proposedContentOffset.x, 0);
rect.size = self.collectionView.frame.size;
NSArray *array = [super layoutAttributesForElementsInRect:rect];
CGFloat centerX = proposedContentOffset.x
+ self.collectionView.frame.size.width * 0.5;
CGFloat minDelta = MAXFLOAT;
for (UICollectionViewLayoutAttributes *attribute in array) {
CGFloat delta = attribute.center.x - centerX;
if (ABS(minDelta) > ABS(delta)) {
minDelta = delta;
}
}
proposedContentOffset.x += minDelta;
return proposedContentOffset;
}
用一個陣列快取所有元素的佈局屬性,並以懶載入建立:
@property (nonatomic, strong) NSMutableArray *attrsArray;
- (NSMutableArray *)attrsArray {
if (_attrsArray == nil) {
_attrsArray = [NSMutableArray array];
}
return _attrsArray;
}
每次 prepareLayout 都清掉舊值並重算全部元素:
- (void)prepareLayout {
[super prepareLayout];
[self.attrsArray removeAllObjects];
NSInteger count = [self.collectionView numberOfItemsInSection:0];
for (NSInteger i = 0; i < count; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
UICollectionViewLayoutAttributes *attrs =
[self layoutAttributesForItemAtIndexPath:indexPath];
[self.attrsArray addObject:attrs];
}
}
以圓心與半徑,用三角函數把元素均勻分佈在圓周上:
- (nullable UICollectionViewLayoutAttributes *)
layoutAttributesForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
NSInteger count = [self.collectionView numberOfItemsInSection:0];
CGFloat radius = 70;
CGFloat oX = self.collectionView.frame.size.width * 0.5;
CGFloat oY = self.collectionView.frame.size.height * 0.5;
UICollectionViewLayoutAttributes *attrs =
[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
attrs.size = CGSizeMake(50, 50);
if (count == 1) {
attrs.center = CGPointMake(oX, oY);
} else {
CGFloat angle = (2 * M_PI / count) * indexPath.item;
CGFloat centerX = oX + radius * sin(angle);
CGFloat centerY = oY + radius * cos(angle);
attrs.center = CGPointMake(centerX, centerY);
}
return attrs;
}
- (nullable NSArray<UICollectionViewLayoutAttributes *> *)
layoutAttributesForElementsInRect:(CGRect)rect {
return self.attrsArray;
}
@property (nonatomic, copy) NSString *imageName;
- (void)awakeFromNib {
// 用 Layer 加上白邊與圓角
self.imageView.layer.borderColor = [UIColor whiteColor].CGColor;
self.imageView.layer.borderWidth = 6;
self.imageView.layer.cornerRadius = 3;
}
- (void)setImageName:(NSString *)imageName {
_imageName = [imageName copy];
self.imageView.image = [UIImage imageNamed:imageName];
}
@property (nonatomic, strong) NSMutableArray *imageNames;
- (NSMutableArray *)imageNames {
if (_imageNames == nil) {
NSMutableArray *imageNames = [NSMutableArray array];
for (NSInteger i = 0; i < 20; i++) {
[imageNames addObject:[NSString stringWithFormat:@"%zd", i + 1]];
}
_imageNames = imageNames;
}
return _imageNames;
}
用 weak 屬性保存,方便隨時替換 layout:
@property (nonatomic, weak) UICollectionView *collectionView;
- (void)setupCollectionView {
CGFloat collectionViewW = self.view.bounds.size.width;
CGFloat collectionViewH = 200;
CGRect frame = CGRectMake(0, 150, collectionViewW, collectionViewH);
LYPCircleLayout *layout = [[LYPCircleLayout alloc] init];
UICollectionView *collectionView =
[[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
self.collectionView = collectionView;
collectionView.dataSource = self;
collectionView.delegate = self;
[self.view addSubview:collectionView];
}
/** 重用識別碼 */
static NSString *const ID = @"photo";
- (void)viewDidLoad {
[super viewDidLoad];
[self setupCollectionView];
[self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LYPPhotoCell class])
bundle:nil]
forCellWithReuseIdentifier:ID];
}
- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section {
return self.imageNames.count;
}
- (UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView
cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
// 有回收就重用,沒有則自動建立
LYPPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID
forIndexPath:indexPath];
cell.imageName = self.imageNames[indexPath.item];
return cell;
}
- (void)collectionView:(nonnull UICollectionView *)collectionView
didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
[self.imageNames removeObjectAtIndex:indexPath.item];
[self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
}
- (void)touchesBegan:(nonnull NSSet<UITouch *> *)touches
withEvent:(nullable UIEvent *)event {
if ([self.collectionView.collectionViewLayout isKindOfClass:[LYPLineLayout class]]) {
// 目前是流水佈局 → 切換成圓形佈局
[self.collectionView setCollectionViewLayout:[[LYPCircleLayout alloc] init] animated:YES];
} else {
// 目前是圓形佈局 → 切換成流水佈局
LYPLineLayout *layout = [[LYPLineLayout alloc] init];
// 不設定 itemSize 則會自動計算
layout.itemSize = CGSizeMake(130, 130);
[self.collectionView setCollectionViewLayout:layout animated:YES];
}
}