【www.bbyears.com--ios】
大家都知道,collectionview在创建时,需要再创建一个collectionviewcell的类来自定义cell的初始化。但是,并不是创建一个collectionviewcell的类就可以正常使用了,这里提供一种我自己使用使用的一些操作,来完成collectionviewcell的创建。
一、在cell的.m文件中加上初始化的代码
// // HomePage1CollectionViewCell.m // leopard // // Created by X on 15/9/6. // Copyright (c) 2015年 ZMIT. All rights reserved. // #import "HomePage1CollectionViewCell.h" @implementation HomePage1CollectionViewCell - (void)awakeFromNib { // Initialization code } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // 在此添加 // 初始化时加载collectionCell.xib文件 NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"HomePage1CollectionViewCell" owner:self options: nil];// 红色字段键入自己设定的cell名。 // 如果路径不存在,return nil if(arrayOfViews.count < 1){return nil;} // 如果xib中view不属于UICollectionViewCell类,return nil if(![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]){ return nil; } // 加载nib self = [arrayOfViews objectAtIndex:0]; } return self; } @end
完成这个操作还是不能成功初始化,进入下一步。
二、在要使用的controller中注册自己定义的cell
//1.register collection [ registerClass:[HomePage1CollectionViewCell class] forCellWithReuseIdentifier:@"HomePage1CollectionViewCell"];
至此就差一步了。
三、在数据源方法中初始化cell
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { HomePage1CollectionViewCell* cell = (HomePage1CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"HomePage1CollectionViewCell"forIndexPath:indexPath]; return cell; }
好了,OK。