在 iOS 開發(fā)中,我們對 UICollectionView 這個控件肯定是非常熟悉。除了可以用它來實現(xiàn)常見的列表布局,也可以用它來實現(xiàn)絕大多數(shù)的自定義列表布局。這篇文章就講講如何使用 UICollectionView 來實現(xiàn)自定義的石工布局,石工布局效果如下所示。

創(chuàng)建 UICollectionView
在 Main.storyboard 里面創(chuàng)建一個 UICollectionViewController 的子類 ViewController, 設(shè)置 Cell 的 identifier 為 " Cell ", 布局設(shè)置為默認(rèn)的 UICollectionViewFlowLayout 類。

接下來實現(xiàn) UICollectionView 的 UICollectionViewDataSource 和 UICollectionViewDelegate 協(xié)議,為了能夠設(shè)置不同的 cell 具有不同的 size,還需要實現(xiàn) UICollectionViewDelegateFlowLayout 協(xié)議。
@interface ViewController () <UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@end
.... 省略
// 多少個 section
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
// section 里面有多少個 cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 5;
}
// cell 的內(nèi)容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier
forIndexPath:indexPath];
cell.backgroundColor = [UIColor greenColor];
return cell;
}
// cell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
// cell 的寬度為 100,高度隨機于 100 - 250
CGFloat randomHeight = 100 + (arc4random() % 150);
return CGSizeMake(100, randomHeight);
}
從下圖的運行效果圖可以看出,UICollectionView 的流式布局 UICollectionViewDelegateFlowLayout 會默認(rèn)取一行中高度最高的 cell 作為這一行布局的高,其余的 cell 上下居中。很明顯這種布局效果并不是我們想要的石工布局,我們需要自定義 UICollectionViewLayout 。

實現(xiàn) UICollectionViewLayout 子類 MasonryViewLayout
要實現(xiàn)我們最開始圖示中的石工布局,我們需要手動計算 UICollectionView 中所有 cell 的位置,可以通過新建一個 MasonryViewLayout 類并繼承 UICollectionViewLayout 來實現(xiàn)。
MasonryViewLayout 類的職責(zé)是
- 手動計算 UICollectionView 中所有 cell 的 frame
- 手動計算 UICollectionView 的 size
要實現(xiàn) MasonryViewLayout 的工作職責(zé),需要覆寫 UICollectionViewLayout 的以下三個方法
- (void)prepareLayout;
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;
- (CGSize)collectionViewContentSize;
prepareLayout 方法會在 UICollectionView 開始布局的時候進(jìn)行調(diào)用,我們可以在這個方法中計算每個 cell 的 frame,計算 cell 的 x ,y, width, height。
- (void)prepareLayout
{
// UICollectionView 多少列
self.numberOfColumns = 3;
// cell 之間的行間距和列間距
self.interItemSpacing = 12;
//緩存每行cell
self.lastYValueForColumn = [NSMutableDictionary dictionary];
// 當(dāng)前列
CGFloat currentColumn = 0;
// collectionView 的寬度
CGFloat fullWidth = self.collectionView.frame.size.width;
// collectionView 的寬度 - 所有 cell 的間距 = 留給 cell 的寬度
CGFloat availableSpaceExcludingPadding = fullWidth - (self.interItemSpacing * (self.numberOfColumns + 1));
// 計算 cell 的寬度
CGFloat itemWidth = availableSpaceExcludingPadding / self.numberOfColumns;
// 緩存每個 indexpath 對應(yīng) cell 的 frame
self.layoutInfo = [NSMutableDictionary dictionary];
NSIndexPath *indexPath;
NSInteger numberOfSections = [self.collectionView numberOfSections];
for (NSInteger section = 0; section < numberOfSections; section ++) {
NSInteger numItems = [self.collectionView numberOfItemsInSection:section];
for (NSInteger item = 0; item < numItems; item++) {
// 計算 indexpath 對應(yīng) cell 的 frame 并緩存在 layoutInfo
indexPath = [NSIndexPath indexPathForItem:item inSection:section];
UICollectionViewLayoutAttributes *itemAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
// 計算 cell 的 x
CGFloat x = self.interItemSpacing + (self.interItemSpacing + itemWidth) * currentColumn;
// 獲取 cell 的 y
CGFloat y = [[self.lastYValueForColumn objectForKey:@(currentColumn)] doubleValue];
// cell 的高度通過 delegate 從外部獲取
CGFloat height = [(id<MasonryViewLayoutDelegate>)self.collectionView.delegate collectionView:self.collectionView layout:self heightForItemAtIndexPath:indexPath];
itemAttributes.frame = CGRectMake(x, y, itemWidth, height);
// 為同一列的下一個 cell 計算 y 值
y += height;
y += self.interItemSpacing;
[self.lastYValueForColumn setObject:@(y) forKey:@(currentColumn)];
currentColumn ++;
if (currentColumn == self.numberOfColumns) {
currentColumn = 0;
}
// 緩存 indexpath 對應(yīng) cell 的 frame 在 layoutInfo
self.layoutInfo[indexPath] = itemAttributes;
}
}
}
第二個 layoutAttributesForElementsInRect: 方法,在 UICollectionView 滾動的時候,系統(tǒng)會調(diào)用 layoutAttributesForElementsInRect: 方法并傳入UICollectionView 的可見矩形區(qū)域 rect ,我們在這個方法返回可見矩形區(qū)域 rect中的所有 cell 的 frame。
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
// 遍歷字典 layoutInfo
NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.layoutInfo.count];
[self.layoutInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath, UICollectionViewLayoutAttributes *attributes, BOOL *stop) {
// 判斷 rect 和 attributes.frame 是否有相交,若是有相交那么需要返回對應(yīng)的 cell 的 frame
if (CGRectIntersectsRect(rect, attributes.frame)) {
[allAttributes addObject:attributes];
}
}];
return allAttributes;
}
第三個 collectionViewContentSize 方法用來確定 UICollectionView 的大小。cell 的 y 值緩存在 lastYValueForColumn 中,如果該 currentColumn 已經(jīng)沒有 cell 的話,那么該 lastYValueForColumn[@(currentColumn)] 就是該列的高。通過對比多列的高,最大的列高即為 UICollectionView 的高。
- (CGSize)collectionViewContentSize
{
//通過比較列的高,獲取 UICollectionView 的高
NSUInteger currentColumn = 0;
CGFloat maxHeight = 0;
do {
CGFloat height = [[self.lastYValueForColumn objectForKey:@(currentColumn)] doubleValue];
if (height > maxHeight) {
maxHeight = height;
}
currentColumn ++;
} while (currentColumn < self.numberOfColumns);
return CGSizeMake(self.collectionView.frame.size.width, maxHeight);
}
使用
在 Main.storyboard 中設(shè)置 UICollectionViewController 的布局為 MasonryViewLayout 類

查看運行效果

總結(jié)
UICollectionView 是一個非常靈活的控件,整個布局過程可以通過 UICollectionViewLayout 來干預(yù)。在 UICollectionViewLayout 子類中通過手動計算各個 cell 的 frame 來達(dá)到自定義布局的效果。通過這種方式,理論上可以實現(xiàn)你想要的任何自定義布局.從 UICollectionViewLayoutAttributes 的頭文件定義中我們可以知道除了自定義 cell 的 frame,還可以自定義cell 的 center,size,transform3D,bounds,transform,alpha,zIndex 屬性
...... 省略代碼
NS_CLASS_AVAILABLE_IOS(6_0) @interface UICollectionViewLayoutAttributes : NSObject <NSCopying, UIDynamicItem>
@property (nonatomic) CGRect frame;
@property (nonatomic) CGPoint center;
@property (nonatomic) CGSize size;
@property (nonatomic) CATransform3D transform3D;
@property (nonatomic) CGRect bounds NS_AVAILABLE_IOS(7_0);
@property (nonatomic) CGAffineTransform transform NS_AVAILABLE_IOS(7_0);
@property (nonatomic) CGFloat alpha;
@property (nonatomic) NSInteger zIndex; // default is 0
...... 省略代碼