ios collectionView

ios开发中,collectionView是必不可少的一个控件。在你没用到的时候他很陌生,用了之后会发觉,她就是tableView扩展出来的。不多说了,首先,先建立一个collectionViewCell 如图:
这里写图片描述

然后在.m控制器中添加collectionView

// 第一步: 遵守协议

@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) UICollectionView *collectionView;


@end


static NSString *CellIdentifier = @"Cell - Identifier";
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self initCollectionView];
}

- (void)initCollectionView
{
    // 第二步 初始化一个布局类 (可以再这个类中设置cell的大小,边距)
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];

    // 保证每行只显示3个cell 每个cell间隔 10距离
    CGFloat width = (self.view.frame.size.width - 20) / 3;

    layout.itemSize = CGSizeMake(width, 200);
    layout.minimumLineSpacing = 10;  // 上下间隔 10

    // 第三步 实例化 collection
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];



    // 注册cell
    [self.collectionView registerNib:[UINib nibWithNibName:@"CustomeCell" bundle:nil] forCellWithReuseIdentifier:CellIdentifier];


}
//返回组数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//返回row数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 30;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CustomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];

    CGFloat red = (arc4random_uniform(255) + 1) / 255.0;
    CGFloat green = (arc4random_uniform(155) + 1) / 255.0;
    CGFloat blue = (arc4random_uniform(200) + 1 )/ 255.0;

    // 随机颜色
    UIColor *randomColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];

    cell.imageView.backgroundColor = randomColor;
    return cell;
}

// cell的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"当前点击了%ld + 1 个cell",indexPath.row);
}


看看效果 ,如图:
这里写图片描述

在这里只是简单的介绍控件,详细可以看苹果开发者文档中,collectionView的API.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值