IOS-UICollectionView的基本使用以及添加headerView

UICollectionView 說白了就是照片牆

在展示類的App中也很常見,比如:瀑布流。

下面說一下如何簡單的使用 和如何添加headerView 讓他也擁有類似於tableview的headerView的效果

UIKIT_EXTERN NSString *const UICollectionElementKindSectionHeader;  //定義好Identifier 

static NSString *const HeaderIdentifier = @"HeaderIdentifier";



 UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];  //此處自動佈局,我沒有寫任何東西 佈局樣式都在cell中

    _collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height-70) collectionViewLayout:layout];


    self.collectionView.dataSource = self;  

    self.collectionView.delegate = self;   

    self.collectionView.showsVerticalScrollIndicator = NO;

    //此處需要註冊纔可以使用  

    [self.collectionView registerClass:[DiaperColectionCell class] forCellWithReuseIdentifier:BrankViewCellIdentifier]; 

    [self.collectionView registerClass:[MYBrandHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeaderIdentifier];

    [self.view addSubview:self.collectionView];


下面執行代理方法 跟tableview 一樣的

#pragma mark -

#pragma mark collectionViewDelegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    //section數量

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    //數據數量

}

//設置元素大小

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    

    return (返回一個Item的 寬高)

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

//此處就是自定義好的cell

}



-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//UICollectionView被選中時調用的方法

}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

{

    MYBrandHeaderView *headReusableView;

//此處是headerView

    if (kind == UICollectionElementKindSectionHeader) {

        headReusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HeaderIdentifier forIndexPath:indexPath];

        headReusableView.frame = CGRectZero;

        headReusableView.delegate = self;

        headReusableView.modeNumber = 1;

        [((MYBrandHeaderView *)headReusableView) setData:self.headerDict];

    }

    return headReusableView;

}


//執行的 headerView 代理  返回 headerView 的高度

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section

{

    CGFloat height = [self.topView getHeight];

    return CGSizeMake(320, height);

}



發佈了43 篇原創文章 · 獲贊 11 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章