iOS UICollectionView基础

UICollectionView是类似于UITableView的强大控件,使用UICollectionView可以实现下图中类似于淘宝购物界面上下左右参差不齐的小方框显示内容:在这里插入图片描述
话不多说,下面就讲UICollectionView的基本创建。

UICollectionView的创建

viewController.h文件中:(遵守UICollectionView相关的两个协议)

#import <UIKit/UIKit.h>
//#import "CollectionViewCell.h"
@interface ViewController : UIViewController
<UICollectionViewDataSource, UICollectionViewDelegate>

@end

viewController.m文件中:

#import "ViewController.h"

#define selfWidth [UIScreen mainScreen].bounds.size.width
#define selfHeight [UIScreen mainScreen].bounds.size.height
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //创建一个layout布局类
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        //设置每个item的大小为100*100
        layout.itemSize = CGSizeMake(100, 100);
        //创建collectionView 通过一个布局策略layout来创建
        UICollectionView * collect = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
        //代理设置
        collect.delegate = self;
        collect.dataSource = self;
        //注册item类型 这里使用系统的类型(也可以使用类似于UITableView的自定义cell)
        [collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
       
        [self.view addSubview:collect];
}

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

//返回每个分区的item个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 10;
}

//返回每个item(item的自定义函数,类似于UITableView的cell的自定义函数)
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    //这样设定出来的是颜色各不相同的item
    cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
    return cell;
}

@end

我们的运行结果如下:
请添加图片描述
从上方的代码可以看出我们UICollectionView的创建过程基本和UITableView是一致的,唯一的不同之处就是UICollectionView的创建需要首先定义一个layout布局类去设定我们的UICollectionView的布局样式和item的规格等等,然后在创建UICollectionView控件的时候使用这个layout布局,其余的部分类似于UITableView都是设定组数,设定组内item的个数和编写item的自定义函数即可完成创建,另外我们在实际项目中,可能经常会用到自定义的方式创建UICollectionView,具体方法推荐这篇博客:iOS之UICollectionView自定义布局

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值