ios中的collectionViewController

来源:互联网 发布:cs demo下载软件 编辑:程序博客网 时间:2024/06/06 07:35

在我们创建一个类继承自UICollectionViewController的.m文件中会有这么一个方法,在viewDidLoad中有一个注册单元格的代码,在缓存池中找是个什么步骤,是先去看缓存池中有没有,如果有,就直接返回,如果没有,就先去看看storyboard中有没有同样ID的cell,这个前提是你建立的collectionViewController在storyboard中绑定了。然后item中还设置了重用的ID,如果有就直接取。还有种情况就是如果缓存池中有,就直接返回,如果没有就看当初有没有注册单元格,如果有,系统就会自动的帮你创建一个这个类型的cell。如果没有的话就返回nil.我们设置collectionView的cell大小和滚动的方向和cell的间距都是用flow layout去改的

注册单元格我们也可以用xib来进行加载,在控制器的viewDidLoad中进行注册

    //获取Nib的对象    UINib * nib=[UINib nibWithNibName:@"ProductCell" bundle:nil];    //注册单元格    [self.collectionView registerNib:nib forCellWithReuseIdentifier:

static NSString * const reuseIdentifier = @"Cell";- (void)viewDidLoad {    [super viewDidLoad];        // Uncomment the following line to preserve selection between presentations    // self.clearsSelectionOnViewWillAppear = NO;        // Register cell classes    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];        // Do any additional setup after loading the view.}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {   UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];        // Configure the cell    cell.backgroundColor=[UIColor redColor];    return cell;}

我们如果纯代码去创建CollectionViewController对象的话一定要给控制器的view设置layout布局

//创建流水布局    UICollectionViewFlowLayout * layout=[[UICollectionViewFlowLayout alloc]init];    //设置layout的size    layout.itemSize=CGSizeMake(100, 100);    //设置layout的最小边距,如果是37.5那就是可以变成三列,如果是大于37.5就只能放两列,因为每个item大小是100的,37.5一行正好可以放三个//    layout.minimumInteritemSpacing=34;//    //设置item中行的间距//    layout.minimumLineSpacing=50;    //设置组的边距    layout.sectionInset=UIEdgeInsetsMake(50, 20, 50, 20);    //创建collectionViewController必须给控制器的view设置布局    TestCollectionViewController* collection=[[TestCollectionViewController alloc]initWithCollectionViewLayout:layout];


原创粉丝点击