【iOS】UICollectionView初学

创建

VIewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
<UICollectionViewDelegate, UICollectionViewDataSource>


@end

VIewController.m



#import "ViewController.h"
#import "CircleCollectionViewLayout.h"
#define Width [UIScreen mainScreen].bounds.size.width
#define Height [UIScreen mainScreen].bounds.size.height



@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemSize = CGSizeMake(100, 160);
    
    UICollectionView* collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    //注册item类型 这里使用系统的类型(也可以使用类似于UITableView的自定义cell)
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
    
    [self.view addSubview:collectionView];
    
}
//返回分区个数
-(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

在这里插入图片描述

自定义布局

  • UICollectionViewFlowLayout:视图布局对象(流水布局:一行排满,自动排到下行),继承自UICollectionViewLayout。UICollectionViewLayout内有一个collectionView属性,所有的视图布局对象都继承自UICollectionViewLayout。
  • 若我们要自定义布局对象,我们一般继承UICollectionViewFlowLayout,然后重写里面的一些方法就可以了。
  • 需要实现三个协议;UICollectionViewDataSource(数据源)、UICollectionViewDelegateFlowLayout(视图布局),自定义布局需要实现UICollectionViewDataSource、UICollectionViewDelegate两个协议即可。

自定义布局

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值