自定義UICollectionViewFlowLayout

很多時候系統(tǒng)的東西是遠遠滿足不了我們項目的需求的,今天要給大家分享的是項目中經(jīng)常遇到的有關(guān)于自定義UICollectionViewFlowLayout問題,例如瀑布流,流水布局等等系統(tǒng)控件所不能實現(xiàn)的效果。

一、效果圖

1、流水布局
2、瀑布流

二、實現(xiàn)思路

1、流水布局

A、確定cell不在首尾時保持cell居中: 通過獲取cell中心距離屏幕中心 (collectionView.contentOffset.x + 屏幕寬度*0.5)最小的距離,然后去改變對應(yīng)cell的proposedContentOffset,使其在沒有滾動超過一定距離(上述cell中心與屏幕中心的距離)時讓對應(yīng)cell的proposedContentOffset始終保持在屏幕中間。
B、通過layoutAttributesForElementsInRect:去設(shè)置每個cell在滾動過程中的布局

注:當(dāng)你是繼承UICollectionViewFlowLayout實現(xiàn)自定義時想要時刻刷新布局,還需要實現(xiàn)shouldInvalidateLayoutForBoundsChange:方法并返回YES,當(dāng)你繼承UICollectionViewLayout則不需要。

2、瀑布流

A、使用columnHeights數(shù)組(有多少列就有多少個元素)記錄cell每次更新布局后對應(yīng)列的高度

B、通過比較columnHeights數(shù)組中記錄的高度來獲取高度最小的那一列,然后計算cell的x值來確定cell的布局

C、實現(xiàn)collectionViewContentSize并返回columnHeights數(shù)組中記錄的最大值(此處不實現(xiàn)則不能滾動)

三、下面上代碼(只講實現(xiàn)思路,不講封裝故.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已經(jīng)計算好的布局屬性
    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) {
        // 當(dāng)前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 需要布局時刻變動需必須實現(xiàn)這個方法,UICollectionViewLayout則不需要
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

2、WaterFallsFlowLayout.m(瀑布流)

#import "WaterFallsFlowLayout.h"
// 默認列數(shù)
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對應(yīng)的布局
- (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;
    
    // 隨機高度,實際請根據(jù)項目自行處理
    CGFloat height = 40 + arc4random() % (120 - 40 + 1);
    
    CGFloat x = 0;
    CGFloat y = 0;
    
    // 設(shè)高度最短的一列為第一列
    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;
}
// 需實現(xiàn)此防范并返回內(nèi)容高度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;
}
結(jié)語: 開始養(yǎng)成好習(xí)慣,不間斷更新文章,為自己,加油!!!
有什么問題或者建議或者更好的思路,歡迎留言探討,謝謝!!!
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,565評論 6 539
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,115評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,577評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,514評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,234評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,621評論 1 326
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,641評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,822評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,380評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,128評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,319評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,879評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,548評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,970評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,229評論 1 291
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,048評論 3 397
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,285評論 2 376

推薦閱讀更多精彩內(nèi)容