美文网首页iOS Developer
UICollectionView 不规则布局实践

UICollectionView 不规则布局实践

作者: maxZhang | 来源:发表于2017-05-25 13:39 被阅读214次

    最近在优化不规则布局排版,之前项目中不规则布局排版一直用的button布局形式,后面一个button的frame根据前一个已经布局好的frame计算而来,类似于用js实现的布局流效果。最近在考虑用collectionView来实现这块,布局后的效果如下:


    未命名.gif

    简单说下CollectionViewLayout,它是负责collectionView的布局类,所有的布局信息由它负责。每一个UICollectionViewLayoutAttributes对应着一个collectionView元素,包括UICollectionViewCell、Supplementary Views 追加视图 (类似于UITableViewHeader或者Footer)、和Decoration Views 装饰视图 (用作背景展示),查看Apple开发文档UICollectionViewLayoutAttributes属性,可以实现诸如frame、size、transform3D、alpha、zIndex(多个CollectionView元素重叠时,可以用此调整显示的顺序)、representedElementCategory(暂时没研究)和representedElementCategory(暂时没研究),上面的效果实现主要用到frame定位,frame也是自定义layout用得最多的layout属性。

    下面以实现上面效果为例,上代码
    自定义layout类的.h文件

    #import <UIKit/UIKit.h>
    @class HHIrregularLayout;
    
    @protocol HHIrregularLayoutDataSource <NSObject>
    
    /**
     获取section的大小
     */
    - (CGSize)layout:(HHIrregularLayout *)collectionViewLayout sizeForSectionAtIndexPath:(NSIndexPath *)indexPath;
    
    /**
     获取item的大小
     */
    - (CGSize)layout:(HHIrregularLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
    
    @end
    
    
    
    @interface HHIrregularLayout : UICollectionViewLayout
    
    @property (assign, nonatomic) CGFloat rowSpacing;//行间距
    @property (assign, nonatomic) CGFloat columnSpacing;//列间距
    @property (assign, nonatomic) id<HHIrregularLayoutDataSource> dataSource;
    
    @end
    

    .h文件主要是定义了HHIrregularLayoutDataSource,用来获取section和每个item的大小信息,以及item的行间距和列间距
    接下来,我们看.m文件
    首先定义延展,用来记录所有的item的frame 和 section的frame 和 所有的属性atts

    @interface HHIrregularLayout ()
    
    @property (strong, nonatomic) NSMutableArray *itemFrames;//可能为二维数组(当为多个section时) 或一维数组(当为1个section时)
    @property (strong, nonatomic) NSMutableArray *sectionFrames;
    @property (strong, nonatomic) NSMutableArray *atts;
    
    @end
    

    下面的init方法只会在alloc时调用,可以在里面初始化一些默认值

    - (instancetype)init
    {
        self = [super init];
        if (self) {
            
            //设置默认数据
            self.rowSpacing = 0;
            self.columnSpacing = 0;
        }
        return self;
    }
    

    懒加载部分如下

    - (NSMutableArray *)sectionFrames
    {
        if (!_sectionFrames) {
            _sectionFrames = [NSMutableArray array];
        }
        return _sectionFrames;
    }
    
    
    - (NSMutableArray *)itemFrames
    {
        if (!_itemFrames) {
            _itemFrames = [NSMutableArray array];
        }
        return _itemFrames;
    }
    
    - (NSMutableArray *)atts
    {
        if (!_atts) {
            _atts = [NSMutableArray array];
        }
        return _atts;
    }
    

    prepareLayout方法用来布局的准备,每次layout变化时都会重新调用,这里主要做每个元素item的计算等

    - (void)prepareLayout
    {
        [super prepareLayout];
        [self setUpItemsFrames];
    }
    
    
    - (void)setUpItemsFrames
    {
        [self.sectionFrames removeAllObjects];
        [self.itemFrames removeAllObjects];
        [self.atts removeAllObjects];
        
        int sectionCount = [self.collectionView numberOfSections];
        
        for (int sectionIndex = 0; sectionIndex < sectionCount; sectionIndex++) {
            
            NSIndexPath *sectionIndexPath = [NSIndexPath indexPathForItem:0 inSection:sectionCount];
            int itemCount = [self.collectionView numberOfItemsInSection:sectionIndex];
    
            CGFloat sectionHeight = [self.dataSource layout:self sizeForSectionAtIndexPath:sectionIndexPath].height;
            
            if (sectionIndex == 0) {
                
                CGRect sectionFrame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, sectionHeight);
                [self.sectionFrames addObject:NSStringFromCGRect(sectionFrame)];
            }
            else {
                int lastItemCount = [self.collectionView numberOfItemsInSection:sectionIndex -1];
    
                CGRect lastItemFrame = CGRectFromString(self.itemFrames[sectionIndex - 1][lastItemCount -1]);
                CGRect sectionFrame = CGRectMake(0, CGRectGetMaxY(lastItemFrame), [UIScreen mainScreen].bounds.size.width, sectionHeight);
                [self.sectionFrames addObject:NSStringFromCGRect(sectionFrame)];
            }
            
            
            UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader withIndexPath:[NSIndexPath indexPathForRow:0 inSection:sectionIndex]];
            att.frame = CGRectFromString(self.sectionFrames[sectionIndex]);
            [self.atts addObject:att];
            
            NSMutableArray *mutableArr = [NSMutableArray array];
            
            for (int itemIndex = 0; itemIndex < itemCount; itemIndex++) {
                
                CGSize size = [self.dataSource layout:self sizeForItemAtIndexPath:[NSIndexPath indexPathForItem:itemIndex inSection:sectionIndex]];
                
                if (itemIndex == 0) {
                    CGRect sectionFrame = CGRectFromString(self.sectionFrames[sectionIndex]);
                    [mutableArr addObject:NSStringFromCGRect(CGRectMake(0, CGRectGetMaxY(sectionFrame), size.width, size.height))];
                }
                else {
                    
                    CGRect lastFrame = CGRectFromString(mutableArr[itemIndex -1]);
                    if (CGRectGetMaxX(lastFrame) + self.columnSpacing + size.width < [UIScreen mainScreen].bounds.size.width) {
                        [mutableArr addObject:NSStringFromCGRect(CGRectMake(CGRectGetMaxX(lastFrame) + self.columnSpacing, CGRectGetMinY(lastFrame), size.width, size.height))];
                    }
                    else {
                        [mutableArr addObject:NSStringFromCGRect(CGRectMake(0, CGRectGetMaxY(lastFrame) + self.rowSpacing, size.width, size.height))];
                    }
                }
                
                UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:itemIndex inSection:sectionIndex]];
                att.frame = CGRectFromString(mutableArr[itemIndex]);
                [self.atts addObject:att];
            }
            [self.itemFrames addObject:mutableArr];
        }
    }
    
    

    -- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds布局对象信息发生改变时是否需要重新局部,建议return YES;

    - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
    {
        return YES;
    }
    

    下面返回CollectionView的ContentSize

    - (CGSize)collectionViewContentSize
    {
        NSMutableArray *frames = self.itemFrames.lastObject;
        CGFloat lastItemMaxY = CGRectGetMaxY(CGRectFromString(frames.lastObject));
        return CGSizeMake(0, lastItemMaxY > self.collectionView.bounds.size.height ? lastItemMaxY:self.collectionView.bounds.size.height + 1);
    }
    

    (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect返回所有的元素的layout属性,包括Supplementary Views和Decoration Views

    - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
    {
        return self.atts;
    }
    

    下面两个方法分别返回Supplementary Views和Decoration Views布局信息

    - (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath
    {
        NSLog(@"section:%ld", (long)indexPath.section);
        UICollectionViewLayoutAttributes *headerAtts = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:elementKind withIndexPath:indexPath];
        headerAtts.frame = CGRectFromString(self.sectionFrames[indexPath.section]);
        return headerAtts;
    }
    
    - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        NSLog(@"section:%ld item:%ld", (long)indexPath.section, (long)indexPath.item);
        UICollectionViewLayoutAttributes *itemAtts = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        itemAtts.frame = CGRectFromString(self.itemFrames[indexPath.section][indexPath.item]);
        return itemAtts;
    }
    

    转载请注明出处,谢谢

    相关文章

      网友评论

        本文标题:UICollectionView 不规则布局实践

        本文链接:https://www.haomeiwen.com/subject/lnzaxxtx.html