美文网首页
最简单的九宫格类布局

最简单的九宫格类布局

作者: 相识虽浅似是经年_凉城 | 来源:发表于2016-06-21 17:43 被阅读1120次

    强大之处

    • 支持水平和垂直两种方向的布局
    • 通过layout配置方式进行布局
    • 类似于TableView中的cell特性外,CollectionView中的Item大小和位置可以自由定义
    • 通过layout布局回调的代理方法,可以动态的定制每个item的大小和collection的布局属性
    - (void)viewDidLoad {
        [super viewDidLoad];
        //创建一个layout布局类
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        //设置每个item的大小为100*100
        layout.itemSize = CGSizeMake(100, 100);
        //创建collectionView 通过一个布局策略layout来创建
        UICollectionView * collect = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
        //代理设置
        collect.delegate=self;
        collect.dataSource=self;
        //注册item类型 这里使用系统的类型(collectionView在完成代理回调前,必须注册一个cell)
        [collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
        [self.view addSubview:collect];
    }
    //返回分区个数
    -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
        return 1;
    }
    //返回每个分区的item个数
    -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
        return 10;
    }
    //返回每个item
    -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
        return cell;
    }
    

    相关文章

      网友评论

          本文标题:最简单的九宫格类布局

          本文链接:https://www.haomeiwen.com/subject/kvygdttx.html