UICollectionView 头部视图

//1.创建layout
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.minimumInteritemSpacing = 8;//item左右间隔
flowLayout.minimumLineSpacing = 8;//item上下间隔
flowLayout.sectionInset = UIEdgeInsetsMake(0,16,0,16);//item对象上下左右的距离
CGFloat cellW = (kScreenW - 16 * 2 - 8) / 2;
CGFloat cellH = cellW + 48;
flowLayout.itemSize = CGSizeMake(cellW, cellH);//每一个 item 对象大小
flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;//设置滚动方向,默认垂直方向.
flowLayout.headerReferenceSize=CGSizeMake(self.view.frame.size.width, 212);//头视图的大小
//        flowLayout.footerReferenceSize=CGSizeMake(self.view.frame.size.width, 30);//尾视图大小
//        layout.headerReferenceSize =CGSizeMake(kScreenW, 160);
//2.设置UICollectionView
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH - 75) collectionViewLayout:flowLayout];
_collectionView.backgroundColor = kTableBgColor;
_collectionView.showsHorizontalScrollIndicator = NO;
_collectionView.dataSource = self;
_collectionView.delegate = self;
[_collectionView registerNib:[UINib nibWithNibName:@"YKFeedListColCell" bundle:nil] forCellWithReuseIdentifier:FeedListCellID];
//注册头部视图
[_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YKFeedListColReusableView class]) bundle:nil]
  forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:FeedListHeaderID];
_collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
_collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerloadMore)];       
#pragma mark - 头部或者尾部视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //如果是头部视图 (因为这里的kind 有头部和尾部所以需要判断  默认是头部,严谨判断比较好)
    if (kind == UICollectionElementKindSectionHeader) {
        YKFeedListColReusableView *headerRV = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:FeedListHeaderID forIndexPath:indexPath];
        headerRV.model = self.topicModel;
        return headerRV;
    }
    return nil;
}

效果如图:

UICollectionView 头部视图_第1张图片
图片.png

你可能感兴趣的:(UICollectionView 头部视图)