iOS:UICollectionView的子类化创建

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的创建

//创建cell

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    ModelStudent *model = self.dataArray[indexPath.item];

//子类化的cell

    YSStudentStatusCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];

    [cell configureWithModel:model.StuUserInfo];

    return cell;

}

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 的使用

flowLayout可以说是collectionView的布局属性,设置不同 flowLayout ,可以加载出不同的collectionView的布局式样



你可能感兴趣的:(IOS:UI设计)