UICollectionView 自定义石工布局

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


石工布局

创建 UICollectionView

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


Main.storyboard

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

@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 的内容
- (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 。


运行效果

实现 UICollectionViewLayout 子类 MasonryViewLayout

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

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

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

- (void)prepareLayout;
- (NSArray<UICollectionViewLayoutAttributes *> *)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<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 对应 cell 的 frame 在 layoutInfo
            self.layoutInfo[indexPath] = itemAttributes;
        }
    }
}

第二个 layoutAttributesForElementsInRect: 方法,在 UICollectionView 滚动的时候,系统会调用 layoutAttributesForElementsInRect: 方法并传入UICollectionView 的可见矩形区域 rect ,我们在这个方法返回可见矩形区域 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 是否有相交,若是有相交那么需要返回对应的 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 是一个非常灵活的控件,整个布局过程可以通过 UICollectionViewLayout 来干预。在 UICollectionViewLayout 子类中通过手动计算各个 cell 的 frame 来达到自定义布局的效果。通过这种方式,理论上可以实现你想要的任何自定义布局.从 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
...... 省略代码

参考

  1. https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/Introduction/Introduction.html
  2. https://book.douban.com/subject/25976913/
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容