以前做瀑布流時用過 UICollectionView,但當時只是套用系統內建的 UICollectionViewFlowLayout。後來看到自訂 FlowLayout 的相關文章,於是動手做了一個圖片瀏覽 Demo,順便把自訂布局的幾個關鍵方法摸熟。
效果是:水平捲動時,遠離中央的項目會逐漸縮小、加上 Y 軸旋轉與降低透明度,捲動停止後自動吸附到置中。

#import <UIKit/UIKit.h> @interface JWCollectionViewFlowLayout : UICollectionViewFlowLayout @end
自訂的做法是繼承 UICollectionViewFlowLayout,然後覆寫四個方法。
#define screenWidth [UIScreen mainScreen].bounds.size.width
#define MaxChangeRange 100
#import "JWCollectionViewFlowLayout.h"
@implementation JWCollectionViewFlowLayout
// 1. 基礎設定
-(void)prepareLayout {
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.itemSize = CGSizeMake(300, 500);
}
// 2. 告訴系統:bounds 改變時必須重新計算布局(捲動動畫的來源)
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
// 3. 核心:逐一調整每個 item 的 transform
- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *array = [super layoutAttributesForElementsInRect:rect];
// 目前可見區域(注意 y 固定為 0,因為是水平捲動)
CGRect visibleRect = CGRectMake(self.collectionView.contentOffset.x, 0,
self.collectionView.bounds.size.width,
self.collectionView.bounds.size.height);
for (UICollectionViewLayoutAttributes *attr in array) {
if (CGRectIntersectsRect(attr.frame, rect)) {
BOOL isAtRight = YES;
CGFloat distance = attr.center.x - CGRectGetMidX(visibleRect);
if (distance < 0) {
distance = -distance;
isAtRight = NO;
}
// 依距離算出比例:離中央越遠越小
CGFloat precent;
if (distance < 180) {
precent = 1.0;
} else {
precent = ((screenWidth / 2) - distance) / (screenWidth / 2);
}
if (precent < 0.5) { precent = 0.5; } // 限制最小比例,避免完全消失
// 透視效果:m34 是 3D 透視矩陣的關鍵
CATransform3D transform = CATransform3DIdentity;
transform.m34 = 1.0 / 600;
transform = CATransform3DScale(transform, 1, precent, 1);
// 依左右側決定 Y 軸旋轉方向
CGFloat p = isAtRight ? M_PI_4 : -M_PI_4;
transform = CATransform3DRotate(transform, p * (1 - precent), 0, 1, 0);
attr.transform3D = transform;
attr.zIndex = 1;
attr.alpha = precent;
}
}
return array;
}
// 4. 捲動停止後的吸附位置
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
withScrollingVelocity:(CGPoint)velocity {
CGFloat offset = MAXFLOAT;
CGFloat hCenter = proposedContentOffset.x + (CGRectGetWidth(self.collectionView.bounds) / 2.0);
CGRect currentRect = CGRectMake(proposedContentOffset.x, 0,
self.collectionView.bounds.size.width,
self.collectionView.bounds.size.height);
NSArray *array = [super layoutAttributesForElementsInRect:currentRect];
for (UICollectionViewLayoutAttributes *layoutAttributes in array) {
CGFloat itemHorizontalCenter = layoutAttributes.center.x;
// 找出距離中心最近的項目
if (ABS(itemHorizontalCenter - hCenter) < ABS(offset)) {
offset = itemHorizontalCenter - hCenter;
}
}
return CGPointMake(proposedContentOffset.x + offset, proposedContentOffset.y);
}
-(void)setupUI {
JWCollectionViewFlowLayout *flowLayout = [[JWCollectionViewFlowLayout alloc] init];
UICollectionView *imgBrowseView = [[UICollectionView alloc] initWithFrame:self.view.bounds
collectionViewLayout:flowLayout];
imgBrowseView.dataSource = self;
imgBrowseView.delegate = self;
imgBrowseView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:imgBrowseView];
_imgBrowseView = imgBrowseView;
[self.imgBrowseView registerNib:[UINib nibWithNibName:@"CustumCollectionViewCell" bundle:nil]
forCellWithReuseIdentifier:@"cell"];
}
Demo:https://github.com/jiangtaidi/JWImageBrowseDemo.git
為什麼要回傳 YES 給 shouldInvalidateLayoutForBoundsChange:?因為我們的效果完全依賴 contentOffset。若回傳 NO,捲動過程中布局不會重算,縮放與旋轉就不會發生。這幾乎是所有「隨捲動變形」效果的起點。
transform.m34 在做什麼?它是 3D 透視矩陣中的透視除法項。設為 1.0 / -500 到 1.0 / 1000 之間的值時,能製造出適度的遠近感;設為 0 則完全沒有透視,旋轉看起來只是單純壓扁。數值絕對值越小,透視越強烈。
為什麼要覆寫 targetContentOffsetForProposedContentOffset:?不覆寫的話,使用者放手後畫面會停在任意位置,可能兩個項目都半置中。覆寫它並找出「離中心最近的那一個」,就能實現吸附效果。這個方法在 UICollectionViewFlowLayout 的公私文件中屬於少數被公開推薦覆寫的方法之一,做輪播、卡片堆疊時幾乎都會用到。
另外提醒一個實務細節:這裡的 precent 是拼字錯誤(應為 percent),複製程式碼時建議一併更正,以免後續維護時造成混淆。
以上就是本文的全部內容,希望對大家的學習有所幫助。