UICollectionView 不規(guī)則布局實(shí)踐

最近在優(yōu)化不規(guī)則布局排版,之前項(xiàng)目中不規(guī)則布局排版一直用的button布局形式,后面一個(gè)button的frame根據(jù)前一個(gè)已經(jīng)布局好的frame計(jì)算而來,類似于用js實(shí)現(xiàn)的布局流效果。最近在考慮用collectionView來實(shí)現(xiàn)這塊,布局后的效果如下:


未命名.gif

簡(jiǎn)單說下CollectionViewLayout,它是負(fù)責(zé)collectionView的布局類,所有的布局信息由它負(fù)責(zé)。每一個(gè)UICollectionViewLayoutAttributes對(duì)應(yīng)著一個(gè)collectionView元素,包括UICollectionViewCell、Supplementary Views 追加視圖 (類似于UITableViewHeader或者Footer)、和Decoration Views 裝飾視圖 (用作背景展示),查看Apple開發(fā)文檔UICollectionViewLayoutAttributes屬性,可以實(shí)現(xiàn)諸如frame、size、transform3D、alpha、zIndex(多個(gè)CollectionView元素重疊時(shí),可以用此調(diào)整顯示的順序)、representedElementCategory(暫時(shí)沒研究)和representedElementCategory(暫時(shí)沒研究),上面的效果實(shí)現(xiàn)主要用到frame定位,frame也是自定義layout用得最多的layout屬性。

下面以實(shí)現(xiàn)上面效果為例,上代碼
自定義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和每個(gè)item的大小信息,以及item的行間距和列間距
接下來,我們看.m文件
首先定義延展,用來記錄所有的item的frame 和 section的frame 和 所有的屬性atts

@interface HHIrregularLayout ()

@property (strong, nonatomic) NSMutableArray *itemFrames;//可能為二維數(shù)組(當(dāng)為多個(gè)section時(shí)) 或一維數(shù)組(當(dāng)為1個(gè)section時(shí))
@property (strong, nonatomic) NSMutableArray *sectionFrames;
@property (strong, nonatomic) NSMutableArray *atts;

@end

下面的init方法只會(huì)在alloc時(shí)調(diào)用,可以在里面初始化一些默認(rèn)值

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        //設(shè)置默認(rèn)數(shù)據(jù)
        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方法用來布局的準(zhǔn)備,每次layout變化時(shí)都會(huì)重新調(diào)用,這里主要做每個(gè)元素item的計(jì)算等

- (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布局對(duì)象信息發(fā)生改變時(shí)是否需要重新局部,建議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;
}

下面兩個(gè)方法分別返回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;
}

轉(zhuǎn)載請(qǐng)注明出處,謝謝

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容