自定义UICollectionViewFlowLayout

很多时候系统的东西是远远满足不了我们项目的需求的,今天要给大家分享的是项目中经常遇到的有关于自定义UICollectionViewFlowLayout问题,例如瀑布流,流水布局等等系统控件所不能实现的效果。

一、效果图

1、流水布局
2、瀑布流

二、实现思路

1、流水布局

A、确定cell不在首尾时保持cell居中: 通过获取cell中心距离屏幕中心 (collectionView.contentOffset.x + 屏幕宽度*0.5)最小的距离,然后去改变对应cell的proposedContentOffset,使其在没有滚动超过一定距离(上述cell中心与屏幕中心的距离)时让对应cell的proposedContentOffset始终保持在屏幕中间。
B、通过layoutAttributesForElementsInRect:去设置每个cell在滚动过程中的布局

注:当你是继承UICollectionViewFlowLayout实现自定义时想要时刻刷新布局,还需要实现shouldInvalidateLayoutForBoundsChange:方法并返回YES,当你继承UICollectionViewLayout则不需要。

2、瀑布流

A、使用columnHeights数组(有多少列就有多少个元素)记录cell每次更新布局后对应列的高度

B、通过比较columnHeights数组中记录的高度来获取高度最小的那一列,然后计算cell的x值来确定cell的布局

C、实现collectionViewContentSize并返回columnHeights数组中记录的最大值(此处不实现则不能滚动)

三、下面上代码(只讲实现思路,不讲封装故.h文件无提供任何属性及接口,此处忽略)

1、Horizontal3DLayout.m(流水布局)

// 初始化
- (void)prepareLayout
{
    [super prepareLayout];
    self.itemSize = CGSizeMake(260, 165);
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.minimumLineSpacing = -10;
}

// 重写此方法重新定位最后滚动的位置
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
    // 计算出最终显示的矩形框
    CGRect rect;
    rect.origin.y = 0;
    rect.origin.x = proposedContentOffset.x;
    rect.size = self.collectionView.frame.size;
    // 获得super已经计算好的布局属性
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    // 计算collectionView最中心点的x值
    CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width * 0.5;
    // 存放最小的间距值
    CGFloat minDelta = MAXFLOAT;
    for (UICollectionViewLayoutAttributes *attrs in array) {
        if (ABS(minDelta) > ABS(attrs.center.x - centerX)) {
            minDelta = attrs.center.x - centerX;
        }
    }
    // 修改原有的偏移量
    proposedContentOffset.x += minDelta;
    return proposedContentOffset;
}
// 返回所有布局
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray* attributes = [super layoutAttributesForElementsInRect:rect];
    CGFloat collectionViewCenterX = self.collectionView.bounds.size.width*0.5;
    CGFloat scaleDistance = collectionViewCenterX - 20;
    
    for (UICollectionViewLayoutAttributes *attrs in attributes) {
        // 当前cell中心相对屏幕左边的距离
        CGFloat leftDistance = attrs.center.x - self.collectionView.contentOffset.x;
        // cell中心与屏幕中心的距离
        CGFloat middleDistance = 0;
        if (leftDistance - collectionViewCenterX  == 0) {
            middleDistance = 0;
        }else if (ABS(leftDistance - collectionViewCenterX) < collectionViewCenterX) {
            if (leftDistance < collectionViewCenterX) {
                // 左边
                middleDistance = collectionViewCenterX - leftDistance;
            }else if (leftDistance > collectionViewCenterX){
                // 右边
                middleDistance = leftDistance - collectionViewCenterX;
            }
            if (middleDistance > scaleDistance) {
                // 超出屏幕
                middleDistance = scaleDistance;
            }
        }else if (ABS(leftDistance - collectionViewCenterX) > collectionViewCenterX) {
            // 超出屏幕
            middleDistance = scaleDistance;
        }
        CGFloat scale = 0;
        if (middleDistance == 0) {
            scale = 1.0;
        }else{
            scale = 0.8 + ((1- middleDistance/scaleDistance) * 0.2);
        }
        attrs.transform = CGAffineTransformMakeScale(scale, scale);
    }
    return attributes;
}

// 继承UICollectionViewFlowLayout 需要布局时刻变动需必须实现这个方法,UICollectionViewLayout则不需要
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

2、WaterFallsFlowLayout.m(瀑布流)

#import "WaterFallsFlowLayout.h"
// 默认列数
static const NSInteger WaterFallsColumnCount = 3;
// 默认列间距
static const NSInteger WaterFallsColumnMargin = 10;
// 默认行间距
static const NSInteger WaterFallsRowMargin = 10;
// more四周间距
static const UIEdgeInsets WaterFallsEdgeInsets = {10,10,10,10};

@interface WaterFallsFlowLayout ()

@property (nonatomic, strong) NSMutableArray *allAttributes;

@property (nonatomic, strong) NSMutableArray *columnHeights;

@end
// 初始化
- (void)prepareLayout
{
    [super prepareLayout];
    
    // 清除高度
    [self.columnHeights removeAllObjects];
    
    for (int i = 0; i < WaterFallsColumnCount; i++) {
        [self.columnHeights addObject:@(WaterFallsEdgeInsets.top)];
    }
    
    // 清除布局
    [self.allAttributes removeAllObjects];
    
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    for (int i = 0; i < count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
        [self.allAttributes addObject:attributes];
    }
}
// 返回所有布局
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return self.allAttributes;
}
// 每个cell对应的布局
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    CGFloat collectionViewWidth = self.collectionView.bounds.size.width;
    
    CGFloat width = (collectionViewWidth - WaterFallsColumnMargin*(WaterFallsColumnCount-1) - WaterFallsEdgeInsets.left - WaterFallsEdgeInsets.right) / WaterFallsColumnCount;
    
    // 随机高度,实际请根据项目自行处理
    CGFloat height = 40 + arc4random() % (120 - 40 + 1);
    
    CGFloat x = 0;
    CGFloat y = 0;
    
    // 设高度最短的一列为第一列
    CGFloat minHeight = [self.columnHeights[0] doubleValue];
    
    // 最矮的一列
    NSInteger minHeightColumnIndex = 0;
    
    for (int i = 0; i < self.columnHeights.count; i++) {
        CGFloat height = [self.columnHeights[i] floatValue];
        if (height < minHeight) {
            minHeight = height;
            minHeightColumnIndex = i;
        }
    }
    
    x = WaterFallsEdgeInsets.left + (WaterFallsColumnMargin + width) * minHeightColumnIndex;
    
    y = minHeight ;
    if (y != WaterFallsEdgeInsets.top) {
        y += WaterFallsRowMargin;
    }
    
    layoutAttributes.frame = CGRectMake(x, y, width, height);
    
    // 更新高度最小列的高度
    self.columnHeights[minHeightColumnIndex] = @(CGRectGetMaxY(layoutAttributes.frame));
    
    return layoutAttributes;
}
// 需实现此防范并返回内容高度collectionView才能滚动
- (CGSize)collectionViewContentSize
{
    CGFloat maxColumnHeight = [self.columnHeights[0] doubleValue];
    for (NSInteger i = 1; i < WaterFallsColumnCount; i++) {
        // 取得第i列的高度
        CGFloat columnHeight = [self.columnHeights[i] doubleValue];
        
        if (maxColumnHeight < columnHeight) {
            maxColumnHeight = columnHeight;
        }
    }
    return CGSizeMake(0, maxColumnHeight + WaterFallsEdgeInsets.bottom);
}
// Get/Set
- (NSMutableArray *)allAttributes
{
    if (!_allAttributes) {
        _allAttributes = [NSMutableArray array];
    }
    return _allAttributes;
}

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

推荐阅读更多精彩内容