UICollectionView 自定义石工布局

在 iOS 开发中,我们对 UICollectionView 这个控件肯定是非常熟悉。除了可以用它来实现常见的列表布局,也可以用它来实现绝大多数的自定义列表布局。这篇文章就讲讲如何使用 UICollectionView 来实现自定义的石工布局,石工布局效果如下所示。


UICollectionView 自定义石工布局_第1张图片
石工布局

创建 UICollectionView

在 Main.storyboard 里面创建一个 UICollectionViewController 的子类 ViewController, 设置 Cell 的 identifier 为 " Cell ", 布局设置为默认的 UICollectionViewFlowLayout 类。


UICollectionView 自定义石工布局_第2张图片
Main.storyboard

接下来实现 UICollectionView 的 UICollectionViewDataSource 和 UICollectionViewDelegate 协议,为了能够设置不同的 cell 具有不同的 size,还需要实现 UICollectionViewDelegateFlowLayout 协议。

@interface ViewController () 
@end
.... 省略
// 多少个 section
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}
// section 里面有多少个 cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 5;
}
// cell 的内容
- (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 会默认取一行中高度最高的 cell 作为这一行布局的高,其余的 cell 上下居中。很明显这种布局效果并不是我们想要的石工布局,我们需要自定义 UICollectionViewLayout 。


UICollectionView 自定义石工布局_第3张图片
运行效果

实现 UICollectionViewLayout 子类 MasonryViewLayout

要实现我们最开始图示中的石工布局,我们需要手动计算 UICollectionView 中所有 cell 的位置,可以通过新建一个 MasonryViewLayout 类并继承 UICollectionViewLayout 来实现。
MasonryViewLayout 类的职责是

  1. 手动计算 UICollectionView 中所有 cell 的 frame
  2. 手动计算 UICollectionView 的 size

要实现 MasonryViewLayout 的工作职责,需要覆写 UICollectionViewLayout 的以下三个方法

- (void)prepareLayout;
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect;
- (CGSize)collectionViewContentSize;

prepareLayout 方法会在 UICollectionView 开始布局的时候进行调用,我们可以在这个方法中计算每个 cell 的 frame,计算 cell 的 x ,y, width, height。

- (void)prepareLayout
{
    // UICollectionView 多少列
    self.numberOfColumns = 3;
    // cell 之间的行间距和列间距
    self.interItemSpacing = 12;
    //缓存每行cell
    self.lastYValueForColumn = [NSMutableDictionary dictionary];
    // 当前列
    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 对应 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 对应 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)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 对应 cell 的 frame 在 layoutInfo
            self.layoutInfo[indexPath] = itemAttributes;
        }
    }
}

第二个 layoutAttributesForElementsInRect: 方法,在 UICollectionView 滚动的时候,系统会调用 layoutAttributesForElementsInRect: 方法并传入UICollectionView 的可见矩形区域 rect ,我们在这个方法返回可见矩形区域 rect中的所有 cell 的 frame。

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    // 遍历字典 layoutInfo
    NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.layoutInfo.count];
    [self.layoutInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath, UICollectionViewLayoutAttributes  *attributes, BOOL *stop) {
        // 判断 rect 和 attributes.frame 是否有相交,若是有相交那么需要返回对应的 cell 的 frame
        if (CGRectIntersectsRect(rect, attributes.frame)) {
            [allAttributes addObject:attributes];
        }
    }];
    return allAttributes;
}

第三个 collectionViewContentSize 方法用来确定 UICollectionView 的大小。cell 的 y 值缓存在 lastYValueForColumn 中,如果该 currentColumn 已经没有 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 中设置 UICollectionViewController 的布局为 MasonryViewLayout 类


UICollectionView 自定义石工布局_第4张图片
设置石工布局

查看运行效果


UICollectionView 自定义石工布局_第5张图片
石工布局

总结

UICollectionView 是一个非常灵活的控件,整个布局过程可以通过 UICollectionViewLayout 来干预。在 UICollectionViewLayout 子类中通过手动计算各个 cell 的 frame 来达到自定义布局的效果。通过这种方式,理论上可以实现你想要的任何自定义布局.从 UICollectionViewLayoutAttributes 的头文件定义中我们可以知道除了自定义 cell 的 frame,还可以自定义cell 的 center,size,transform3D,bounds,transform,alpha,zIndex 属性

...... 省略代码
NS_CLASS_AVAILABLE_IOS(6_0) @interface UICollectionViewLayoutAttributes : NSObject 

@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
...... 省略代码

参考

  1. https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/Introduction/Introduction.html
  2. https://book.douban.com/subject/25976913/

你可能感兴趣的:(UICollectionView 自定义石工布局)