一、纯代码的实现
首先,讲一下UICollectionView的纯代码的创建,创建CollectionView,得先创建UICollectionViewLayout,
UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
layout.itemSize = CGSizeMake(100, 100);
layout.minimumLineSpacing = 10;
layout.minimumInteritemSpacing = 10;
layout.sectionHeadersPinToVisibleBounds = YES;
layout.sectionFootersPinToVisibleBounds = YES;
再创建CollectionView,CollectionView和TableView类似,只是CollectionView由CollectionViewFlowLayout来管理,建议大家使用UICollectionViewDelegateFlowLayout来对CollectionView进行管理,具体细节请看链接的代码。
self.DQCollectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
[self.view addSubview:self.DQCollectionView];
self.DQCollectionView.delegate = self;
self.DQCollectionView.dataSource = self;
[self.DQCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
self.DQCollectionView.backgroundColor = [UIColor whiteColor];
[self.DQCollectionView registerNib:[UINib nibWithNibName:@"DQHeaderFooterView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
[self.DQCollectionView registerNib:[UINib nibWithNibName:@"DQHeaderFooterView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
请看效果,
图1 图2不过两个设置,要iOS 9.0才有效
@property (nonatomic) BOOL sectionHeadersPinToVisibleBounds NS_AVAILABLE_IOS(9_0);
@property (nonatomic) BOOL sectionFootersPinToVisibleBounds NS_AVAILABLE_IOS(9_0);
二、xib的实现
首先拉进CollectionView,再设置CollectionViewFlowLayout。
图3 图4再设置 sectionHeadersPinToVisibleBounds/sectionFootersPinToVisibleBounds
图5NO:跟随CollectionView滚动,YES:header 悬挂头部,footer 悬挂尾部
QQ技术支持:350218638
网友评论