网格

首先添加图片到Assets.xcassets
在ViewController.m

#import "ViewController.h"

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource> // 4.遵守协议

@end

static NSString *reuseCell = @"123";

@implementation ViewController

接下来是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];
    
    // 注/Users/pxy/Desktop/UI下/工程/课堂练习 - 网格/课堂练习 - 网格/Base.lproj/Main.storyboard册网格cell
    [clv registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseCell];
    
    clv.backgroundColor = [UIColor blackColor];
    
    //'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;
    
}

运行效果图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值