UICollectionView添加 HeaderView FooterView


UICollectionView顯示HeaderView FooterView 不如UITableView那么容易,常用會有兩種做法:

1.Xib或者Storyboard 在屬性一欄中設置一下:

75D44C55-6F45-4F99-BBAD-C70CC6668540.png
如圖所示,

2.代碼設計Section的header和Footer:

好多都在找UICollectionView是否有這么個屬性,比如上圖說到Accessories什么的,其實不然。大家首先要搞明白意見事情,header和footer是追加視圖,屬於layout中的所以要代碼設置section要在UICollectionViewFlowLayout:

- (UICollectionViewFlowLayout *) flowLayout{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.。。。。。。//各屬性設置
    flowLayout.headerReferenceSize = CGSizeMake(320.0f, 50.0f);  //設置headerView大小
    flowLayout.footerReferenceSize = CGSizeMake(320.0f, 50.0f);  // 設置footerView大小
    return flowLayout;
}   
如果你用的是Xib或者Storyboard,不想在上圖屬性設置,想用代碼:
- (void)viewDidLoad 
{
    [super viewDidLoad];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.headerReferenceSize = CGSizeMake(320.0f, 50.0f);  //設置headerView大小
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];  //  一定要設置
    [self.collectionView setCollectionViewLayout:layout];
  //(這部分說明可以參見xib設置sectionview)
}

- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WINSIZE.width, WINSIZE.width*7/15)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:[UMOnlineConfig getConfigParams:@"GuizeImageUrl"]] placeholderImage:kDefaultImage192_124];
    [headerView addSubview:imageView];
    return headerView;
}

運行結果:

C69DD622-3F70-432E-900E-60E76E181012.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM