UIKit_UICollectionView瀑布流,水平流水布局

再次声明,仅当记录笔记用


不规则布局的流水布局

  • 高度一致,则规则布局
  • 高度不一致,则瀑布流布局
不设置任何属性
打开rowHeight属性,则规则
//初始化
- (void)initCollectinView {
    _myWaterView = ({  
        //布局规则,文件在下面
        DFWaterFlowLayout *flowLayout = [[DFWaterFlowLayout alloc]init];
        //打开这属性则规则
        //flowLayout.rowHeight = ([UIScreen mainScreen].bounds.size.width-40)/3.0;

        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,
                                                                                             0,
                                                                                             CGRectGetWidth(self.view.frame),
                                                                                             CGRectGetHeight(self.view.frame))
                                                             collectionViewLayout:flowLayout];
        collectionView.backgroundColor = [UIColor redColor];
        collectionView.dataSource = self;
        collectionView.delegate   = self;
        [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:collectionCellID3];
        [self.view addSubview:collectionView];
        collectionView;
    });
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  return 100;
}

//返回每一个 item 的 cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellID3 forIndexPath:indexPath];
  cell.backgroundColor = [UIColor yellowColor];
  return cell;
}

- (CGFloat)waterFlowLayout:(DFWaterFlowLayout *)waterFlowLayout indexPath:(NSIndexPath *)indexPath width:(CGFloat)width {
    return 100;
}

DFWaterFlowLayout(瀑布流布局类)

//.h文件,继承UICollectionViewLayout

@class DFWaterFlowLayout;
@protocol DFWaterFlowLayoutDelegate <NSObject>
@required
/*!
 *  @brief 每个Item的高度(传入高度一至,则规则;不规则就瀑布流)
 *
 *  @param waterFlowLayout waterFlowLayout对象
 *  @param indexPath       indexPath
 *  @param width           width
 *
 *  @return 高度
 */
- (CGFloat)waterFlowLayout:(DFWaterFlowLayout *)waterFlowLayout indexPath:(NSIndexPath *)indexPath width:(CGFloat)width;

@end

/*!
 *  @brief 不规则布局的流水布局
 */
@interface DFWaterFlowLayout : UICollectionViewLayout

/*!
 瀑布流的每排个数(默认3)
 */
@property (nonatomic,assign) NSInteger maxColumns;
/*!
 瀑布流竖直方向的间距(上下间距,默认10)
 */
@property (nonatomic,assign) CGFloat verticalMargin;
/*!
 瀑布流水平方向的间距(左右间距,默认10)
 */
@property (nonatomic,assign) CGFloat horzontalMargin;
/*!
 瀑布流Cell整体偏移量(相对UICollectionView容器的偏移量)
 */
@property (nonatomic,assign) UIEdgeInsets inserts;
/*!
 瀑布流高度Item高度(如果实现代理,则失效)
 */
@property (nonatomic,assign) CGFloat rowHeight;
/*!
 设置代理,界获取高度(不实现代理方法,则每个Item的高度随机)
 */
@property (nonatomic,  weak) id<DFWaterFlowLayoutDelegate> delegate;

@end
//.m实现文件
@interface DFWaterFlowLayout () {
    //水平间距
    CGFloat _horizontalMargin ;
    //竖直间距
    CGFloat _verticalMargin ;
    //最大的列数
    NSInteger _maxColumns ;
    //每个item的四边距
    UIEdgeInsets _insets;
}
//保存每一列的高度
@property (strong, nonatomic) NSMutableArray *perColumnMaxHeights;
//保存所有元素的相关属性
@property (strong, nonatomic) NSMutableArray<UICollectionViewLayoutAttributes*> *layoutAtts;

@end

@implementation DFWaterFlowLayout

- (instancetype)init {
    if (self = [super init]) {
        _maxColumns = 3;
        _horizontalMargin = 10;
        _verticalMargin = 10;
        _insets = UIEdgeInsetsMake(0, 10, 0, 10);
    }
    return self;
}

- (NSMutableArray *)layoutAtts{
    if (!_layoutAtts) {
        _layoutAtts = [NSMutableArray array];
    }
    return _layoutAtts;
}

- (NSMutableArray *)perColumnMaxHeights{
    if (!_perColumnMaxHeights) {
        _perColumnMaxHeights = [NSMutableArray array];
    }
    return _perColumnMaxHeights;
}

// 因为在 “layoutAttributesForElementsInRect”可能调用多次,计算多次, 而导致每次的随机数,都不一样, 而造成覆盖现象
// 所以在 预布局中处理, 可以只计算一次
- (void)prepareLayout
{
    [self.perColumnMaxHeights removeAllObjects];
    [self.layoutAtts removeAllObjects];
    
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    //初始化数组高度,因为第一行,不需要按照高度大小添加
    for (int i = 0; i < _maxColumns; i ++) {
        [self.perColumnMaxHeights addObject:@(_insets.top)];
    }
    
    CGFloat W = (self.collectionView.frame.size.width - _insets.left - _insets.right - (_maxColumns - 1) * _horizontalMargin ) / _maxColumns;
    CGFloat H ;
    CGFloat X,Y;
    
    for (int i = 0; i < count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *layoutAtt = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        
        // 求出高度最小的列, 计算出 Y值
        Y = [self.perColumnMaxHeights[[self minColumn]] floatValue]+ _verticalMargin;
        // 计算出 X 值
        X = _insets.left +[self minColumn] * (W + _horizontalMargin) ;
        // 通过代理计算出 高度
        if ([self.delegate respondsToSelector:@selector(waterFlowLayout:indexPath:width:)]) {
            H = [self.delegate waterFlowLayout:self indexPath:indexPath width:W];
        } else if (_rowHeight > 0){
            H = _rowHeight;
        } else {
            H = 70 + arc4random_uniform(100);
        }
        // 将新算出来的高度,替换 原来数组中对应的最低高度位置
        [self.perColumnMaxHeights replaceObjectAtIndex:[self minColumn] withObject:@(Y + H)];
        
        layoutAtt.frame = CGRectMake(X, Y, W, H);
        
        [self.layoutAtts addObject:layoutAtt];
    }
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
    
    return self.layoutAtts;
}

// 计算最小高度的列
- (NSInteger)minColumn {
    
    NSInteger minColumn = 0;
    CGFloat minHeight = [self.perColumnMaxHeights[0] floatValue];
    for (int i = 1; i < self.perColumnMaxHeights.count; i ++) {  
        CGFloat height = [self.perColumnMaxHeights[i] floatValue];
        if (height < minHeight) {
            minHeight = height;
            minColumn = i;
        }
    }
    return minColumn;
}

//计算最大高度的列 ,(用在设置 contensize)
- (NSInteger)maxColumn {
    
    NSInteger maxColumn = 0;
    CGFloat maxHeight = [self.perColumnMaxHeights[0] floatValue];
    for (int i = 1; i < self.perColumnMaxHeights.count; i ++) {
        CGFloat height = [self.perColumnMaxHeights[i] floatValue];
        if (height > maxHeight) {
            maxHeight = height;
            maxColumn = i;
        }
    }
    return maxColumn;
}


- (CGSize)collectionViewContentSize {
    
    if (self.perColumnMaxHeights.count == 0) {
        return CGSizeZero;
    }
    return CGSizeMake(self.collectionView.bounds.size.width,  [self.perColumnMaxHeights[[self maxColumn]] floatValue] + _insets.bottom);
}

- (void)setHorzontalMargin:(CGFloat)horizontalMargin {
    
    _horizontalMargin = horizontalMargin;
}

- (void)setVerticalMargin:(CGFloat)verticalMargin{
    
    _verticalMargin = verticalMargin;
}

- (void)setMaxColumns:(NSInteger)maxColumns{
    if (maxColumns == 0) {
        return;
    }
    _maxColumns = maxColumns;
}

-(void)setInserts:(UIEdgeInsets)inserts {
    
    _insets = inserts;
}

@end

UICollectionView水平缩放布局

水平布局.png
//使用
- (void)initHorizenCollectionView {
    _myHorizontalView = ({
        //设置布局 : 流水布局(布局类在下面)
        DFHorizontalLayout *flowLayout = [[DFHorizontalLayout alloc]init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width/3.0, [UIScreen mainScreen].bounds.size.width/3.0);
        
        //创建 collectionView 初始化时加入布局
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, self.view.bounds.size.width/3.0)
                                                             collectionViewLayout:flowLayout];
        collectionView.backgroundColor = [UIColor blackColor];
        collectionView.dataSource = self;
        [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:collectionCellID1];
        [self.view addSubview:collectionView];
        collectionView;
    });
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
      return 200;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellID1 forIndexPath:indexPath];
    cell.backgroundColor = [UIColor yellowColor];
    return cell;
}

DFHorizontalLayout.h文件(继承UICollectionViewFlowLayout)

/*!
 *  @brief 水平布局(从左到右)
 */
@interface DFHorizontalLayout : UICollectionViewFlowLayout

@end

DFHorizontalLayout.m文件(实现文件)

@implementation DFHorizontalLayout

//返回区域内每一个元素的布局属性 (重写的话, 相当于 要给每一个元素增添属性)
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    // 系统父类写的方法, 系统子类必须调用父类,进行执行(只是对部分属性进行修改,所以不必一个个进行设置布局属性)
    NSArray *layoutAtts =  [super layoutAttributesForElementsInRect:rect];
    CGFloat collectionViewCenterX = self.collectionView.bounds.size.width * 0.5;
    CGFloat contentOffsetX = self.collectionView.contentOffset.x;
    for (UICollectionViewLayoutAttributes *layoutAtt in layoutAtts) {
        CGFloat centerX = layoutAtt.center.x;
        // 形变值,根据当前cell 距离中心位置,的远近  进行反比例缩放。 (不要忘记算其偏移量的值。)
        CGFloat scale = 1 - ABS((centerX - collectionViewCenterX - contentOffsetX)/self.collectionView.bounds.size.width);
        // 给 布局属性  添加形变
        layoutAtt.transform = CGAffineTransformMakeScale(scale, scale);
    }
    return layoutAtts;
}

/**
 现在实现另一个功能.想让每次都有一个图片放在 collectionView 的中间,也就是总有一张大的图片.,也就是上图的情况. (需要让其停止拖拽的时候, 让图片的偏移量 进行一定的修改, 离中线最近的 cell, 移至中心). 关于偏移量的方法, 我们找到其相关方法,再次进行重写的
 */
//通过目标移动的偏移量, 提取期望偏移量  (一般情况下,期望偏移量,就是 目标偏移量)
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
    
    //根据偏移量 , 确定区域
    CGRect rect = CGRectMake(proposedContentOffset.x, 0, self.collectionView.frame.size.width, self.collectionView.frame.size.height);
    //将屏幕所显示区域的 元素布局 取出。
    NSArray *layoutAtts = [super layoutAttributesForElementsInRect:rect];
    CGFloat minMargin = MAXFLOAT;
    CGFloat collectionViewCenterX = self.collectionView.frame.size.width * 0.5;
    CGFloat contentOffsetX = proposedContentOffset.x;
    //取出区域内元素, 并根据其中心位置, 与视图中心位置 进行比较, 比出最小的距离差
    for (UICollectionViewLayoutAttributes *layoutAtt in layoutAtts) {
        CGFloat margin = layoutAtt.center.x - contentOffsetX - collectionViewCenterX;
        if (ABS(margin) < ABS(minMargin)) {
            minMargin = margin;
        }
    }
    NSLog(@"%f",minMargin);
    //期望偏移量 加上差值, 让整体,沿差值 反方向移动,这样的话, 最近的一个,刚好在中心位置
    proposedContentOffset.x += minMargin;
    return proposedContentOffset;
}

/**
//打开此处,为圆形布局,计算方式如下图
// 进行圆形布局,设置其每个元素的相关因素(主要是它的 frame,中心点)
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    // 创建可变数组,用于储存所有的布局因素
    NSMutableArray *layoutAtts = [NSMutableArray array];
    // 取出对应布局中的 collectionView 的元素的数目(为的就是给一个个cell 独立设置其的布局)
    NSInteger count =  [self.collectionView numberOfItemsInSection:0];
    // 设置每个 cell 的高度和宽度
    CGFloat WH = 50;
    // 取出圆形视图的中心点 (也就是 collectionView 的中心点)
    CGFloat centerX = self.collectionView.frame.size.width * 0.5;
    CGFloat centerY = self.collectionView.frame.size.height * 0.5;
    // 设置 圆形布局半径
    CGFloat randius = centerY- 30;
    // 获得每个 cell 之间的间距 (所有 cell 平分了整个圆)
    CGFloat angelMargin = M_PI * 2 / count;
    // 遍历进行设置布局
    for (int i = 0; i < count ; i ++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        //创建对应索引的布局
        UICollectionViewLayoutAttributes *layoutAtt = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        //根据三角函数设置布局的中心点
        CGFloat a = sin(i * angelMargin) * randius;
        CGFloat b = cos(i * angelMargin) * randius;
        layoutAtt.center = CGPointMake(centerX + a, b+ centerY);
        layoutAtt.size = CGSizeMake(WH, WH);
        [layoutAtts addObject:layoutAtt];
    }
    return layoutAtts;
}
*/

// 是否允许 运行时,(在无效(未确定)的layout 情况下)改变bounds
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    
    return YES;
}

@end

圆形计算图示

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

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,611评论 4 59
  • 前言 UICollectionView是个强大的视图,除了提供默认的UICollectionViewFlowLay...
    Tidus阅读 6,081评论 2 57
  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,629评论 1 92
  • 今天是我们分开的第98天,短短三个月,感觉像一生那么漫长。 是的,老公远行了,这一次不比以前的出差,多则半...
    西厢堂主阅读 327评论 8 4
  • 第一次接触茶道,是零五年的元旦。那一天我在单位值班,傍晚回家的路上,想着应该给师兄打个电话,问候一下。随即在车上拨...
    秦沐阳阅读 680评论 2 0