1 colleectionview 和tableview的不同之处在于需要自定义cell 给cell注册重用标识 和添加自定义Layout
layout里主要 设置item的size 和header的size 还有行间距
2在viewController中实现collectionView的三个协议
初始化layout
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//设置collectionView滚动方向
// [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
//设置headerView的尺寸大小
layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 100);
//该方法也可以设置itemSize
layout.itemSize =CGSizeMake(110, 150);
// 行间距
layout.minimumLineSpacing = 5;
// 水平间距
layout.minimumInteritemSpacing = 0;
_collectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, kTopHeight, SCREEN_WIDTH, 50) collectionViewLayout:layout];
//隐藏 滚动条
_collectionview.showsHorizontalScrollIndicator = NO;
_collectionview.delegate = self;
_collectionview.dataSource = self;
_collectionview.backgroundColor = UIColorWhite;
[_collectionview registerClass:[StoreSearchDetailCollectionViewCell class] forCellWithReuseIdentifier:@"StoreSearchDetailCollectionViewCell"];
3.在设置header的时候 注意样式
注意重用 可以使用 懒加载 根据tag值 取label 的值
{
UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView" forIndexPath:indexPath];
headerView.backgroundColor =[UIColor grayColor];
UILabel *label = [headerView viewWithTag:3000];
if (!label) {
label = [[UILabel alloc] initWithFrame:headerView.bounds];
label.tag = 3000;
label.font = [UIFont systemFontOfSize:20];
[headerView addSubview:label];
}
label.text = [NSString stringWithFormat:@"这是collectionView的头部:%zd,%zd",indexPath.section,indexPath.row];
return headerView;
}
网友评论