IOS-自定義CollectionView的layout以及添加頭部

  • 先看例子,再看知識點(diǎn)


    成型的collectionView
  • 在viewDidLoad里
- (void)viewDidLoad {
    [super viewDidLoad];
    //這里從本地獲取數(shù)據(jù)存在數(shù)組self.Array里
    NSArray * shopsArray = [shopModel mj_objectArrayWithFilename:@"1.plist"];
    [self.Array addObjectsFromArray:shopsArray];
    
    //這是自定義瀑布流
    FlowLayout *flowlayout1 = [[FlowLayout alloc] init];
    //這個(gè)代理為了能夠根據(jù)數(shù)組內(nèi)圖片的寬高等比縮放
    flowlayout1.delegate = self;
    self.mainView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flowlayout1];
    self.mainView.backgroundColor = [UIColor redColor];
    self.mainView.delegate = self;
    self.mainView.dataSource = self;
    self.mainView.scrollEnabled = YES;
    
    [self.view addSubview:self.mainView];
    //注冊一個(gè)Cell
    [self.mainView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"CollectionCell"];
    //注冊一個(gè)ReusableView,類型是UICollectionElementKindSectionHeader的(頭部)
    [self.mainView registerClass:[headReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headReusableView"];
    //注冊一個(gè)ReusableView,類型是UICollectionElementKindSectionFooter的(尾部)
//    [self.mainView registerClass:[footReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footReusableView"];
    
}
  • collectionView的代理
#pragma mark  設(shè)置CollectionView的組數(shù)
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
#pragma mark  設(shè)置CollectionView每組所包含的個(gè)數(shù)
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.Array.count;
}
#pragma mark  設(shè)置CollectionView所展示出來的cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];
    cell.model = self.Array[indexPath.item];
    return cell;
}
#pragma mark  定義每個(gè)UICollectionView的大小
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    return CGSizeMake(100, 100);
//}
#pragma mark  定義整個(gè)CollectionViewCell與整個(gè)View的間距
//- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
//    return UIEdgeInsetsMake(10, 10, 10, 10);
//}
#pragma mark  設(shè)置CollectionViewCell是否可以被點(diǎn)擊
//- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    return YES;
//}
#pragma mark  點(diǎn)擊CollectionView觸發(fā)事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"---------------------");
}
#pragma mark headView大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(self.view.frame.size.width, 100);
}
//#pragma mark footView大小
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
//    return CGSizeMake(self.view.frame.size.width, 80);
//}
#pragma mark headView和footView都在這里判斷
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    headReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headReusableView" forIndexPath:indexPath];
//    footReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footReusableView" forIndexPath:indexPath];
//    [footerView.btn1 addTarget:self action:@selector(btn1Click) forControlEvents:UIControlEventTouchUpInside];
    [headerView.Btn1 addTarget:self action:@selector(Btn1Click) forControlEvents:UIControlEventTouchUpInside];
//    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        return headerView;
//    }else{
//        return footerView;
//    }
}
  • 自己定義的代理(為了計(jì)算等比寬高)
#pragma mark wxzFlowLayoutDelegate
- (CGFloat)WXZWaterFlow:(UICollectionViewFlowLayout *)waterFlow heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath{
    shopModel *model = self.Array[indexPath.item];
    return model.h * width / model.w ;
}
  • 在UICollectionViewFlowLayout.h中
#import <UIKit/UIKit.h>
@class UICollectionViewFlowLayout;

@protocol WXZWaterFlowDelegte <NSObject>
- (CGFloat)WXZWaterFlow:(UICollectionViewFlowLayout *)waterFlow heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath;
@end

@interface FlowLayout : UICollectionViewFlowLayout

@property(weak, nonatomic)id<WXZWaterFlowDelegte>delegate;

@end
  • 在UICollectionViewFlowLayout.m中
#import "FlowLayout.h"

#define WXZCollectionW self.collectionView.frame.size.width

/** 每一行之間的間距 */
static const CGFloat  WXZDefaultRowMargin = 5;
/** 每一列之間的間距 */
static const CGFloat  WXZDefaultColumnMargin = 10;
/** 每一列之間的間距 top, left, bottom, right */
static const UIEdgeInsets  WXZDefaultInsets = {5, 15, 5, 5};
/** 默認(rèn)的列數(shù) */
static const int WXZDefaultColumsCount = 2;

@interface FlowLayout()
/** 每一列的最大Y值 */
@property (nonatomic, strong) NSMutableArray *columnMaxYs;
/** 存放所有cell的布局屬性 */
@property (nonatomic, strong) NSMutableArray *attrsArray;

@property (nonatomic, strong) NSArray *heightArray;

@end

@implementation FlowLayout
#pragma mark -lazy
- (NSMutableArray *)columnMaxYs
{
    if (!_columnMaxYs) {
        _columnMaxYs = [[NSMutableArray alloc] init];
    }
    return _columnMaxYs;
}

- (NSMutableArray *)attrsArray
{
    if (!_attrsArray) {
        _attrsArray = [[NSMutableArray alloc] init];
    }
    return _attrsArray;
}

- (NSArray *)heightArray
{
    if (!_heightArray) {
        _heightArray = [[NSArray alloc] init];
        _heightArray = @[@85,@105,@115,@105];
    }
    return _heightArray;
}

#pragma mark - 實(shí)現(xiàn)內(nèi)部的方法
/**
 * 決定了collectionView的contentSize。由于collectionView將item的布局任務(wù)委托給layout對象,那么滾動區(qū)域的大小對于它而言是不可知的。自定義的布局對象必須在這個(gè)方法里面計(jì)算出顯示內(nèi)容的大小,包括supplementaryView和decorationView在內(nèi)。
 */
- (CGSize)collectionViewContentSize
{
    // 找出最長那一列的最大Y值
    CGFloat destMaxY = [self.columnMaxYs[0] doubleValue];
    for (NSUInteger i = 1; i<self.columnMaxYs.count; i++) {
        // 取出第i列的最大Y值
        CGFloat columnMaxY = [self.columnMaxYs[i] doubleValue];
        
        // 找出數(shù)組中的最大值
        if (destMaxY < columnMaxY) {
            destMaxY = columnMaxY;
        }
    }
    return CGSizeMake(0, destMaxY + WXZDefaultInsets.bottom);
}
/**
 * 系統(tǒng)在準(zhǔn)備對item進(jìn)行布局前會調(diào)用這個(gè)方法,我們重寫這個(gè)方法之后可以在方法里面預(yù)先設(shè)置好需要用到的變量屬性等。比如在瀑布流開始布局前,我們可以對存儲瀑布流高度的數(shù)組進(jìn)行初始化。有時(shí)我們還需要將布局屬性對象進(jìn)行存儲,比如卡片動畫式的定制,也可以在這個(gè)方法里面進(jìn)行初始化數(shù)組。切記要調(diào)用[super prepareLayout];
 */
//
- (void)prepareLayout
{
    [super prepareLayout];
    
    // 重置每一列的最大Y值
    [self.columnMaxYs removeAllObjects];
    for (NSUInteger i = 0; i<WXZDefaultColumsCount; i++) {
        [self.columnMaxYs addObject:@(WXZDefaultInsets.top)];
    }
    
    // 計(jì)算所有cell的布局屬性
    [self.attrsArray removeAllObjects];
    NSUInteger count = [self.collectionView numberOfItemsInSection:0];
    for (NSUInteger i = 0; i < count; ++i) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
        [self.attrsArray addObject:attrs];
    }
}
/**
 * 說明所有元素(比如cell、補(bǔ)充控件、裝飾控件)的布局屬性。個(gè)人覺得完成定制布局最核心的方法,沒有之一。collectionView調(diào)用這個(gè)方法并將自身坐標(biāo)系統(tǒng)中的矩形傳過來,這個(gè)矩形代表著當(dāng)前collectionView可視的范圍。我們需要在這個(gè)方法里面返回一個(gè)包括UICollectionViewLayoutAttributes對象的數(shù)組,這個(gè)布局屬性對象決定了當(dāng)前顯示的item的大小、層次、可視屬性在內(nèi)的布局屬性。同時(shí),這個(gè)方法還可以設(shè)置supplementaryView和decorationView的布局屬性。合理使用這個(gè)方法的前提是不要隨便返回所有的屬性,除非這個(gè)view處在當(dāng)前collectionView的可視范圍內(nèi),又或者大量額外的計(jì)算造成的用戶體驗(yàn)下降——你加班的原因。
 */
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    //找到collectionVIew的頭部headReusableView并且添加到數(shù)組里,這樣子就能夠顯示出頭部里
    [self.attrsArray addObjectsFromArray:[super layoutAttributesForElementsInRect:rect]];
    return self.attrsArray;
}

/**
 * 說明cell的布局屬性,相當(dāng)重要的方法。collectionView可能會為了某些特殊的item請求特殊的布局屬性,我們可以在這個(gè)方法中創(chuàng)建并且返回特別定制的布局屬性。根據(jù)傳入的indexPath調(diào)用[UICollectionViewLayoutAttributes layoutAttributesWithIndexPath: ]方法來創(chuàng)建屬性對象,然后設(shè)置創(chuàng)建好的屬性,包括定制形變、位移等動畫效果在內(nèi)
 */
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    /** 計(jì)算indexPath位置cell的布局屬性 */
    
    // 水平方向上的總間距
    CGFloat xMargin = WXZDefaultInsets.left + WXZDefaultInsets.right + (WXZDefaultColumsCount - 1) * WXZDefaultColumnMargin;
    // cell的寬度
    
    CGFloat w = (WXZCollectionW - xMargin - 20) / WXZDefaultColumsCount;
    // cell的高度
    CGFloat h = [self.delegate WXZWaterFlow:self heightForWidth:w atIndexPath:indexPath];
    
    // 找出最短那一列的 列號 和 最大Y值  要判斷第一個(gè)才+363
    CGFloat destMaxY = [self.columnMaxYs[0] doubleValue];
    NSUInteger destColumn = 0;
    for (NSUInteger i = 1; i<self.columnMaxYs.count; i++) {
        // 取出第i列的最大Y值
        CGFloat columnMaxY = [self.columnMaxYs[i] doubleValue];
        
        // 找出數(shù)組中的最小值
        if (destMaxY > columnMaxY) {
            destMaxY = columnMaxY;
            destColumn = i;
        }
    }
    
    // cell的x值
    CGFloat x = WXZDefaultInsets.left + destColumn * (w + WXZDefaultColumnMargin);
    
    CGFloat y = destMaxY + WXZDefaultRowMargin;
    
    // cell的frame
    attrs.frame = CGRectMake(x, y, w, h);
    
    // cell的y值
    if (destMaxY==5) {
        //手動增加第一個(gè)cell的高,如果不增加 ,那么cell是從頂部開始 。會與頭部相疊
        attrs.frame = CGRectMake(x, 120, w, h);
    }
    
    // 更新數(shù)組中的最大Y值
    self.columnMaxYs[destColumn] = @(CGRectGetMaxY(attrs.frame));
    
    return attrs;
}

//- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
當(dāng)collectionView的bounds改變的時(shí)候,我們需要告訴collectionView是否需要重新計(jì)算布局屬性,通過這個(gè)方法返回是否需要重新計(jì)算的結(jié)果。簡單的返回YES會導(dǎo)致我們的布局在每一秒都在進(jìn)行不斷的重繪布局,造成額外的計(jì)算任務(wù)。
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    //    NSLog(@"%s",__func__);
    return NO;
}
@end
  • 你可以在CollectionView的頭部headReusableView里添加任何東西 ,他繼承自UIView,如果你的CollectionView的FlowLayout是系統(tǒng)自定義的,那么你就不需要再將自定義的headReusableView添加進(jìn)FlowLayout的數(shù)組里了。系統(tǒng)已經(jīng)將你想要的做好了。
  • CollectionView非常好用,建議多多的學(xué)習(xí)。有如下擴(kuò)展:對每一張圖片的介紹文字有多有少。那么我們的高度還是圖片高度+字體所對應(yīng)的大小

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

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

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