前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS 瀑布流之栅格布局

iOS 瀑布流之栅格布局

作者头像
且行且珍惜_iOS
发布2018-08-13 17:28:05
1.7K0
发布2018-08-13 17:28:05
举报

实现的栅格布局效果示意图

需求示意图

确定需求

由上面的需求示意图可知模块的最小单位是正方形,边长是屏幕宽除去边距间隔后的四等份,而每个模块的样式有小正方形(1:1)、大正方形(2:2)、横长方形(2:1)、纵长方形(1:2),动态的根据服务器下发模块样式绘制布局,可以横向滑动,限定为两行的高度。 注意:上面的示意宽高比是约等于,忽略了间距,计算的时候千万别忘了。

实现思路

由上需求分析可知,我们可以让后台每个模块下发width和height两个字段,字段的值是1或2就行了,然后我们就能根据宽高字段来确定模块的宽高了。现在宽高有了,我们怎么来绘制模块呢? 答案当然是用UICollectionView了,然后自定义流水布局UICollectionViewLayout,主要代码如下:计算记录每一个cell对应的布局属性。这个样式的栅格布局我已封装集成在WSLWaterFlowLayout 中,详情可以前往下载。

代码语言:javascript
复制
/** 返回indexPath位置cell对应的布局属性*/
- (CGRect)itemFrameOfHorizontalGridWaterFlow:(NSIndexPath *)indexPath{
    //collectionView的高度
    CGFloat collectionH = self.collectionView.frame.size.height;
    //设置布局属性item的frame
    CGFloat h = [self.delegate waterFlowLayout:self sizeForItemAtIndexPath:indexPath].height;
    CGFloat w = [self.delegate waterFlowLayout:self sizeForItemAtIndexPath:indexPath].width;
    
    CGFloat x = 0;
    CGFloat y = 0;
  
    //找出宽度最短的那一行
    NSInteger destRow = 0;
    CGFloat minRowWidth = [self.rowWidths[destRow] doubleValue];
    for (NSInteger i = 1; i < self.rowWidths.count; i++) {
        //取出第i行
        CGFloat rowWidth = [self.rowWidths[i] doubleValue];
        if (minRowWidth > rowWidth) {
            minRowWidth = rowWidth;
            destRow = i;
        }
    }
    
    y = destRow == 0 ? self.edgeInsets.top : self.edgeInsets.top + h + self.rowMargin;
    
    x = [self.rowWidths[destRow] doubleValue] == self.edgeInsets.left ? self.edgeInsets.left : [self.rowWidths[destRow] doubleValue] + self.columnMargin;
    //更新最短那行的宽度
    if (h >= collectionH - self.edgeInsets.bottom - self.edgeInsets.top) {
        x = [self.rowWidths[destRow] doubleValue] == self.edgeInsets.left ? self.edgeInsets.left : self.maxRowWidth + self.columnMargin;
        for (NSInteger i = 0; i < 2; i++) {
            self.rowWidths[i] = @(x + w);
        }
    }else{
        self.rowWidths[destRow] = @(x + w);
    }
    //记录最大宽度
    if (self.maxRowWidth < x + w) {
        self.maxRowWidth = x + w ;
    }
    return CGRectMake(x, y, w, h);
}

后台下发字段格式示意图

功能描述:WSLWaterFlowLayout 是在继承于UICollectionViewLayout的基础上封装的带头脚视图的瀑布流控件。目前支持竖向瀑布流(item等宽不等高、支持头脚视图)、水平瀑布流(item等高不等宽 不支持头脚视图)、竖向瀑布流( item等高不等宽、支持头脚视图)、栅格布局瀑布流 4种样式的瀑布流布局。

WSLWaterFlowLayout

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.08.12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 确定需求
  • 实现思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档