UICollectionView纯代码基本使用

2015-11-24  本文已影响538人  为之_iOS
本文讨论控件UICollectionView在其他控制器中的使用.

UICollectionView&UICollectionViewController 基础套餐系列1

0.遵守代理

self.collectionView.delegate = self;
self.collectionView.dataSource = self;

1.注册 cell 类

 //注册 collectionViewCell
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseID];

2.创建 collectionView


- (void)setupCollectionView{
    UICollectionViewFlowLayout *layout = [self layout];
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 104, SCREENW, SCREENH - 104) collectionViewLayout:layout];
    self.collectionView = collectionView;
//    collectionView.scrollEnabled = NO;
    collectionView.pagingEnabled = YES;
//    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.backgroundColor = [UIColor lightGrayColor];
    collectionView.bounces = NO;
    [self.view addSubview:collectionView];
    
}

2.1注意:代码创建itemCell 必须指定 layout

- (UICollectionViewFlowLayout *)layout{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.itemSize = CGSizeMake(100, 200);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    return layout;
}

3.实现代理方法

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
    
    NSLog(@"%@",NSStringFromCGRect(cell.frame));
    
    cell.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];
    
    return cell;
}

4.总结
这是collectionView 纯代码基本使用,有时间会把高阶使用方法陆续总结.

5.再说几句
在OC编程中,大部分 APP 界面数据展示都会使用 UITableViewController 和 UICollectionViewController, 精通此两种控制器使用.就是小霸王了,其乐无穷啊.

上一篇 下一篇

猜你喜欢

热点阅读