ios collectionView

来源:互联网 发布:淘宝客不小心退出了 编辑:程序博客网 时间:2024/05/01 02:20

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

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

// 第一步: 遵守协议@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>@property (nonatomic,strong) UICollectionView *collectionView;@endstatic 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
原创粉丝点击