UICollectionView

- (void)viewDidLoad {

    [super viewDidLoad];

    

    // UICollectionView 的使用

    

    // layout参数

    // UICollectionViewLayout 是一个布局类, 作用是给collectionViewcell提供布局(安排位置, 设置大小....)

    // 这个类本身不能直接使用, 需要创建它的子类,重写相关的方法使用

    

    // 系统自己写好了一个基础的流式布局

    

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    

    // 调整每个cell大小

    flowLayout.itemSize = CGSizeMake(100, 100);

    

    // 调整滚动方向

//    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;

    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

 

    // Cell 之间的间距

    flowLayout.minimumInteritemSpacing = 1;

    

    // Cell 行之间的间距

    flowLayout.minimumLineSpacing = 2;

    

    // 整个section区域的布局, 距离边界的距离(,,,)

    flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);

    

    

    

    // 开始创建UICollectionView对象, 初始化方法中的collectionViewLayout必须先定义好,上面的代码即是定义collectionViewLayout

    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];

    

    self.collectionView.delegate = self;

    self.collectionView.dataSource = self;

    

    [self.view addSubview:self.collectionView];

//    [_collectionView release];

    

    // 必须给collectionView注册一个cell

    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];

 

    // Do any additional setup after loading the view, typically from a nib.

}

 

 

 

 

 

#pragma mark - collectionView 的协议方法(两个必须实现的方法)

 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return 20;

}

 

 

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

{

    

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];

    if (cell == nil) {

        for (id temp  in cell.contentView.subviews) {

            [temp removeFromSuperlayer];

        }

        

        cell =[[UICollectionViewCell alloc] init];

    }

    UILabel *label = [[UILabel alloc] init];

    label.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row];

    label.frame = CGRectMake(45, 45, 10, 10);

    [cell.contentView addSubview:label];

    

    cell.backgroundColor = [UIColor redColor];

    

    return cell;

    

}

posted @ 2015-10-10 17:55  上官元空  阅读(160)  评论(0编辑  收藏  举报