美文网首页
网格视图

网格视图

作者: h_6e8a | 来源:发表于2017-11-23 15:30 被阅读0次

    import "ViewController.h"

    @interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
    {
    UICollectionView *collection; //网格视图
    }

    @end

    //设置可重用标识符
    static NSString * const reuseID = @"cell";

    @implementation ViewController

    • (void)viewDidLoad {
      [super viewDidLoad];

      //创建一个布局对象
      UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init];

      //设置每个格子的大小
      flowlayout.itemSize = CGSizeMake(100, 100);

      //设置每个格子的最小水平间距
      flowlayout.minimumInteritemSpacing = 20;

      //设置行间距 最小行间距
      flowlayout.minimumLineSpacing = 20;

      //设置组与组之间的间隔
      flowlayout.sectionInset = UIEdgeInsetsMake(50, 10, 0, 10);
      //创建网格对象
      collection = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:flowlayout];

      //设置代理
      collection.delegate = self;
      collection.dataSource = self;

      //设置网格背景颜色
      collection.backgroundColor = [UIColor greenColor];

      //注册cell
      [collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseID];

      //将网格添加到父视图上
      [self.view addSubview:collection];
      }

    //=========数据源方法=========

    //设置组数

    • (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
      {
      return 5;
      }

    //设置行数

    • (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
      {
      return 5;
      }

    //设置 cell 内容

    • (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
      {
    //根据可重用标识符查找cell
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
    
    //设置cell的背景颜色
    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;
    

    }

    相关文章

      网友评论

          本文标题:网格视图

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