UICollectionView的创建基本与UITableView的创建方式相同
首先,创建继承于UICollectionView的子类
然后在初始化方法中设置一些属性
- (id)initWithFrame:(CGRect)frame
{
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.minimumInteritemSpacing = 0; //列间距
flowLayout.minimumLineSpacing = 0; //行间距
self = [super initWithFrame:frame collectionViewLayout:flowLayout];
if (self) {
//隐藏滑块
self.showsHorizontalScrollIndicator = NO;
self.showsVerticalScrollIndicator = NO;
//设置代理
self.delegate = self;
self.dataSource = self;
//设置背景颜色(默认黑色)
self.backgroundColor = [UIColor whiteColor];
//注册单元格
[self registerClass:[YSStudentStatusCell class] forCellWithReuseIdentifier:identify];
}
return self;
}
collectionView的协议方法基本与tableView的相同,主要区别在于cell的创建与头视图的创建
先看cell的创建
<p class="p1"></p><p class="p1">//创建cell</p><p class="p1">- (<span class="s1">UICollectionViewCell</span> *)collectionView:(<span class="s1">UICollectionView</span> *)collectionView cellForItemAtIndexPath:(<span class="s1">NSIndexPath</span> *)indexPath</p><p class="p1">{</p><p class="p1"> <span class="s2">ModelStudent</span> *model = <span class="s3">self</span>.<span class="s2">dataArray</span>[indexPath.<span class="s1">item</span>];</p><p class="p1"> //子类化的cell</p><p class="p2"><span class="s4"> </span><span class="s2">YSStudentStatusCell</span><span class="s4"> *cell = [collectionView </span>dequeueReusableCellWithReuseIdentifier<span class="s4">:</span><span class="s2">identify</span><span class="s4"> </span>forIndexPath<span class="s4">:indexPath];</span></p><p class="p1"> [cell <span class="s5">configureWithModel</span>:model.<span class="s2">StuUserInfo</span>];</p><p class="p1"> <span class="s3">return</span> cell;</p><p class="p1">}</p>
collectionView的子类化cell创建的初始化方法如下,我用init不执行
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self initView];
}
return self;
}
collectionView头视图的创建,首先需要注册头视图,注册demo我一般与cell注册写在一块
//collection头视图的注册
[self registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Identifierhead"];
创建头视图的协议方法
//组的头视图创建
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Identifierhead" forIndexPath:indexPath];
headView.backgroundColor = [UIColor blueColor];
return headView;
}
flowLayout可以说是collectionView的布局属性,设置不同 flowLayout ,可以加载出不同的collectionView的布局式样