UIcollectionView實現(xiàn)不規(guī)則排列的算法

UIcollectionView實現(xiàn)不規(guī)則排列的算法

UIcollectionView實現(xiàn)不規(guī)則排列的算法,簡單的來說就是實現(xiàn)cell尺寸的規(guī)律變化,讓其在幾種尺寸中變種,并實現(xiàn)其排序的一種算法。說的不如看的,下面這張圖將告訴你什么UIcollectionView實現(xiàn)不規(guī)則排列的算法。
效果如下:

效果一:
兩列效果


Simulator Screen Shot 2016年5月19日 20.02.20.png

效果二:
三列效果


Simulator Screen Shot 2016年5月19日 14.56.21.png

效果三:
四列效果


Simulator Screen Shot 2016年5月19日 19.53.07.png

效果四:
內(nèi)邊距效果


效果五:
section與section之間無間距


Simulator Screen Shot 2016年5月19日 19.59.22.png

本例已經(jīng)上傳github,如果需要看詳細代碼,請前往下載。

在看本例之前,確保你對UICollectionViewLayout有一定的基礎(chǔ)。好了,下面開始正式的講解

UICollectionView不規(guī)則算法的實現(xiàn)

我們知道UICollectionView和UITableView比較相似,但是UICollectionView的功能更加的強大,基本能實現(xiàn)任何的cell的布局。UICollectionView由四個核心的部分組成:UICollectionView、UICollectionDelegate、UICollectionViewDataSources、UICollectionViewLayout。給部分協(xié)同工作,以實現(xiàn)用戶任意的布局樣式。各部分的功能如下:
UICollectionView: 協(xié)調(diào)UICollectionViewDataSources與UICollectionViewLayout的工作,從UICollectionViewDataSources獲取數(shù)據(jù),向UICollectionViewLayout索取布局信息,將數(shù)據(jù)、布局信息交個UICollectionViewCell進行顯示。
UICollectionViewDataSources: 向UICollectionView提供數(shù)據(jù)信息。
UICollectionViewLayout: 向UICollectionView提供布局信息。
UICollectionViewDelegate:告知用戶感興趣的時刻,例如cell被點擊。

根據(jù)上面的描述,UICollectionView不規(guī)則排列算法的實現(xiàn)主要是通過UICollectionViewLayout類完成,因此我們的講解主要是UICollectionViewLayout。

==另外,在間接之間,一個必須明白的前提是:cell的大小不是預(yù)先確定的,即不是有UICollectionView提供的,也不是從網(wǎng)絡(luò)獲取的,而是UICollectionViewLayout在布局的時候根據(jù)概率自動生成的。==

++算法詳解++
1 > 我們將UICollectionView的視圖分為固定的列數(shù):三列,那么每列的寬度得以確定為width,在這之后,可以確定我們cell要顯示的大小種類:width X width、2width X width、2width X 2width,每種尺寸大小的cell是通過概率隨機生成的。

2 > 使用一個數(shù)組記錄每列對應(yīng)的最大的高度。

- (NSMutableArray *)eachLineHight {
    if (_eachLineHight == nil) {
        _eachLineHight = [NSMutableArray array];
        for (int i = 0; i < self.numOfItemInLine; i++) {
            [_eachLineHight addObject:@(0)];
        }
    }
    return _eachLineHight;
}

在這個懶加載中,首先初始化了每列的最高高度為0;

3 > 當布局一個cell的時候:

第一步,通過上面的數(shù)組檢測最短的一列。

// 判斷最短的一類
    CGFloat shortest = CGFLOAT_MAX;
    NSInteger index = 0;
    for (NSInteger i = 0; i < self.numOfItemInLine ; i++) {
        CGFloat temp = [self.eachLineHight[i] floatValue];
        if (temp < shortest) {
            shortest = temp;
            index = i;
        }
    }

第二步,通過隨機數(shù)生成高度,確定x,y值

    X = index * width + self.sectionInset.left;
    Y = shortest;

    // 根據(jù)概率生成cell的高度
    NSInteger num = arc4random_uniform(10);
    if (self.twoMulTwoChange * 10 > num) {
        H = width * 2;
    } else {
        H = width * 1;
    }

這里需要說明的是,上面代碼中sectionInset是代理(即UICollectionView)提供的內(nèi)邊距

第三步,通過第一步獲得的最短一列,檢測這一列的下一列和本列高度是否相等;如果相等,那個么通過概率確定當前布局的cell的寬度是為width 還是 2 X width,如果不相等,那么cell的寬度為直接為width。到此cell的寬度確定了。在確定了寬度后更新記錄每列最大高度的數(shù)組。這步代碼如下

    // 是否可以顯示寬高比為2:1的cell
    NSInteger flag = arc4random_uniform(10);
    if ((index + 1) < self.numOfItemInLine && [self.eachLineHight[(index + 1)] integerValue] == [self.eachLineHight[index] integerValue] && flag < 10 * self.oneMulTwoChange) { // 可以
        
        W = 2 * width;
        // 更新列數(shù)組高度
        self.eachLineHight[index] = @(shortest + H);
        self.eachLineHight[index + 1] = @(shortest + H);
        
    } else { // 不可以
        
        W = width;
        // 排除高度是寬度的兩倍的cell,將其改為寬高相等的cell
        if (H == 2 * width) {
            H = width;
        }
        // 更新列數(shù)組高度
        self.eachLineHight[index] = @(shortest + H);
    }

需要解釋的一下,上面if判斷句中的條件:
(index + 1) < self.numOfItemInLine是確保當前列是否為最后一列,因為當當前列為最后一列的時候,就沒有必要判斷了,cell的寬度直接就等于width。

[self.eachLineHight[(index + 1)] integerValue] == [self.eachLineHight[index] integerValue]是判斷當前列和下一列是否相等。在這里的一個重要點是,這里的integerValue是必須的,因為如果使用floatValue的話,概率實在是太低了,兩個浮點數(shù)要相等是十分難的,你會看見顯示的cell中沒有一個是 2width X width 或 2width X 2width的。因此,此處必須使用整型。

flag < 10 * self.oneMulTwoChange是概率判斷。

還有一點需要注意的是,由于我們不需要cell的size為 width X 2width 的cell,所以在上面的代碼中一會看一這么一段代碼:

        // 排除高度是寬度的兩倍的cell,將其改為寬高相等的cell
        if (H == 2 * width) {
            H = width;
        }

另外,在上面的兩個參數(shù)oneMulTwoChange、 twoMulTwoChange 是兩個概率因子,一個決定顯示width X 2width cell的概率,一個決定顯示 2width X 2width的概率,這兩個是通過代理有UICollectionView提供的。

這里UICollectionView不規(guī)則排列的算法就實現(xiàn)了。接下來說一說本demo中的一些相關(guān)功能的實現(xiàn)。

Demo中相關(guān)功能的實現(xiàn)

本例中相關(guān)的功能:
1 > 可以決定本section是否緊接著上個section開始布局。
2 > 可以分別給每個section添加內(nèi)邊距

這兩個功能都是通過協(xié)議由代理決定的。且兩個功能存在同一段代碼中,這里就一起講解兩個功能的實現(xiàn),先看代碼


    NSInteger section = [self.collectionView numberOfSections];
    for (NSInteger i = 0; i < section; i++) {
        
        // 獲取sectionInset
        if ([self.delegate respondsToSelector:@selector(sectionInsetForSection:)]) {
            self.sectionInset = [self.delegate sectionInsetForSection:i];
        }
        
        // 給section添加頂部邊距
        [self addSectionTopInsetWithSection:i];
        
        // 計算當前section的每個cell的frame
        NSInteger row = [self.collectionView numberOfItemsInSection:i];
        for (NSInteger j = 0; j < row; j++) {
            NSIndexPath * indexPath = [NSIndexPath indexPathForItem:j inSection:i];
            // 獲取對應(yīng)section中對應(yīng)的row的layoutAttribute,并存儲
            UICollectionViewLayoutAttributes * attribute = [self layoutAttributesForItemAtIndexPath:indexPath];
            [self.attributes addObject:attribute];
        }
        
        // 給section添加底部邊距
        [self addSectionBottomInsetWithSection:i];
    
    }

由于我們布局cell的時候是通過遍歷section,在遍歷section中的row進行布局的。所以在一個section開始的時候,給這個section添加一個內(nèi)邊距的top距離,這一步對應(yīng)[self addSectionTopInsetWithSection:i]方法;在一個section布局結(jié)束的時候,給這個section添加上內(nèi)邊距的bottom距離,這一步對應(yīng)方法[self addSectionBottomInsetWithSection:i];

接下來我們看一看上面說的兩個方法具體的實現(xiàn):

/**
 *  給section添加頂部邊距
 */
- (void)addSectionTopInsetWithSection:(NSInteger)section {
    
    // 判斷每個section的開始是否緊跟上一個section
    BOOL isContinueLayout;
    if ([self.delegate respondsToSelector:@selector(isContinueLayoutForNextSection:)]) {
        isContinueLayout = [self.delegate isContinueLayoutForNextSection:section];
    }
    
    if (!isContinueLayout) {
        // 判斷最高的列
        CGFloat longest = 0;
        for (NSInteger i = 0; i < self.eachLineHight.count ; i++) {
            CGFloat temp = [self.eachLineHight[i] floatValue];
            if (temp > longest) {
                longest = temp;
            }
        }
        // 更改每列的高度為最高列的高度加上邊距,以開始下一section
        for (NSInteger i = 0; i < self.eachLineHight.count; i++) {
            self.eachLineHight[i] = @(longest + self.sectionInset.top);
        }
    }
}

這里首先要通過代理方法isContinueLayoutForNextSection判斷是否當前section要緊接著上一個section,如果要緊接著上一個section顯示,那么內(nèi)邊距的top就沒有用,如果不緊接著上一個section開始顯示,那么就更新記錄每列最大高度的數(shù)組中的每一個項為:當前最大高度 + top距離。

第二個方法的實現(xiàn):

/**
 *  給section添加底部邊距
 */
- (void)addSectionBottomInsetWithSection:(NSInteger)section {
    // 判斷每個section的開始是否緊跟上一個section
    BOOL isContinueLayout;
    if ([self.delegate respondsToSelector:@selector(isContinueLayoutForNextSection:)]) {
        isContinueLayout = [self.delegate isContinueLayoutForNextSection:section];
    }
    
    if (!isContinueLayout) {
        // 判斷最高的列
        CGFloat longest = 0;
        for (NSInteger i = 0; i < self.eachLineHight.count ; i++) {
            CGFloat temp = [self.eachLineHight[i] floatValue];
            if (temp > longest) {
                longest = temp;
            }
        }
        // 更改每列的高度為最高列的高度并加上下邊距,以開始下一section
        for (NSInteger i = 0; i < self.numOfItemInLine; i++) {
            self.eachLineHight[i] = @(longest + self.sectionInset.bottom);
        }
    }
}

這里的原理和上面的原理是一樣的,這里就不在解釋了。

另外一點,為了保證最后一個section的bottom邊距有效。在collectionViewContentSize方法中返回的高度應(yīng)該加上內(nèi)邊距的bottom距離

/**
 *  返回scrollView的contentSize
 */
- (CGSize)collectionViewContentSize {
    
    // 判斷最高的一列
    CGFloat longest = 0;
    for (NSInteger i = 0; i < self.eachLineHight.count; i++) {
        CGFloat temp = [self.eachLineHight[i] floatValue];
        if (temp > longest) {
            longest = temp;
        }
    }
    
    return CGSizeMake(self.collectionView.frame.size.width, longest + self.sectionInset.bottom);
}

好了,本博客的就到此結(jié)束,如果你發(fā)現(xiàn)有什么錯誤的地方,請聯(lián)系QQ:352770454,感謝你的閱讀。

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

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

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