网格

遵守网格的协议

@interface ViewController () // 4.遵守协议

创建网格

static NSString *reuseCell = @"123";

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建流水布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    // 格子的大小
    layout.itemSize =  CGSizeMake(80, 100);
    // 行间距
    layout.minimumLineSpacing = 15;
    // 列间距
    layout.minimumInteritemSpacing = 15;

    // 分区间距
    layout.sectionInset =  UIEdgeInsetsMake(15, 30, 30, 15);
    //
    
    
    // 网格视图 (表格 - > 需要注册,需要创建布局)
    // 1.frame
    UICollectionView *clv = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
    
    // 2.数据源和代理
    clv.delegate = self;
    clv.dataSource = self;
    // 3. 添加到主视图
    [self.view addSubview:clv];
    
    // 注册网格cell
    [clv registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseCell];
    
    clv.backgroundColor = [UIColor greenColor];
    
    //'attempt to register a cell class which is not a subclass of UICollectionViewCell (UICollectionView)'

    
}

// 分区个数(几组)
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

// 每个分区有几个item (小格子的个数)
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if(section == 0){
        return 9;
        
    }else{
        
        return 3;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseCell forIndexPath:indexPath];
    
    // cell 添加背景色
    cell.backgroundColor = [UIColor yellowColor];
    // 'could not dequeue a view of kind: UICollectionElementKindCell with identifier 123 - must register a nib or a class for the identifier or
//     80/100
    NSArray *arr = @[@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10"];
    
    UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    imgV.image = [UIImage imageNamed:arr[indexPath.row]];
    [cell addSubview:imgV];
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 80, 80, 20)];
    label.text = arr[indexPath.row];
    // 居中
    label.textAlignment = NSTextAlignmentCenter;
    
    [cell addSubview:label];
    
    
    return cell;
    
}

你可能感兴趣的:(网格)