橫向多行的UICollectionViewFlowLayout

需求

需求

頁面顯示最少0行最多兩行,超過兩行水平方向分頁顯示。

效果

collectionViewGIF.gif

分析

常用功能中應用個數(shù)是不固定的,高度也是不固定的,過多時橫向分頁。

選擇UICollectionView控件來實現(xiàn),使用UICollectionViewFlowLayout布局,設置滾動方向為水平。

問題

使用UICollectionViewFlowLayout進行布局后發(fā)現(xiàn)頁面顯示為

錯誤布局

而我們期望的是

正確布局

解決方法

核心代碼

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger item = indexPath.item;

    /*
     0 2 4 ---\  0 1 2
     1 3 5 ---/  3 4 5 計算轉換后對應的item  原來'4'的item為4,轉換后為3
     */
    NSInteger page = item / (self.itemCountPerRow * self.maxRowCount);
    // 計算目標item的位置 x 橫向偏移  y 豎向偏移
    NSUInteger x = item % self.itemCountPerRow + page * self.itemCountPerRow;
    NSUInteger y = item / self.itemCountPerRow - page * self.rowCount;
    // 根據(jù)偏移量計算item
    NSInteger newItem = x * self.rowCount + y;
    NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:newItem inSection:indexPath.section];

    UICollectionViewLayoutAttributes *newAttributes = [super layoutAttributesForItemAtIndexPath:newIndexPath];
    newAttributes.indexPath = indexPath;

    return newAttributes;
}

UICollectionViewLayoutAttributes是管理collectionView中item的布局相關屬性的布局對象。

我們這里通過重新設置Item對應UICollectionViewLayoutAttributes的indexPath來達到我們想要的效果,需要注意的是為了防止出現(xiàn)數(shù)組越界的情況這里做了使每一行Item都是“滿”的處理(即Item的個數(shù)為itemCountPerRow的整數(shù)倍)。

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger itemCount;
    if (self.dataArray.count == 0) {
        itemCount = 0;
    } else if (self.dataArray.count / (kMaxRowCount * kItemCountPerRow) > 1) {
        itemCount = kMaxRowCount * kItemCountPerRow * ceilf(self.dataArray.count / (kMaxRowCount * kItemCountPerRow));
    } else {
        itemCount = ceilf(self.dataArray.count / kItemCountPerRow) * kItemCountPerRow;
    }
    return itemCount;
}
占位

為了更好的體現(xiàn),這里未對label背景顏色進行透明處理,我們可以從圖中看出6、7的位置實際是返回了UICollectionViewCell。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewLabelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[CollectionViewLabelCell description] forIndexPath:indexPath];
    
    if (indexPath.item < self.dataArray.count) {
        cell.backgroundColor = [UIColor lightGrayColor];
        cell.labelTitle.text = self.dataArray[indexPath.item];
    }else{
        cell.backgroundColor = [UIColor clearColor];
        cell.labelTitle.text = @"";
    }
    return cell;
}

demo地址:https://github.com/ABChe/HorizontallyPageableFlowLayout

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

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

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