以编程方式创建 UICollectionView [英] Creating a UICollectionView programmatically

查看:27
本文介绍了以编程方式创建 UICollectionView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个指南或教程,它将向我展示如何仅使用代码设置一个简单的 UICollectionView.

I'm looking for a guide or tutorial that will show me how to set up a simple UICollectionView using only code.

我正在浏览 Apple 网站上的文档,我正在使用 参考手册 也是如此.

I'm wading through the documentation on Apples site, and I'm using the reference manual as well.

但我真的会从一个简单的指南中受益,该指南可以向我展示如何设置 UICollectionView 而无需使用故事板或 XIB/NIB 文件 - 但不幸的是,当我搜索时,我只能找到具有故事板功能的教程.

But I would really benefit from a simple guide that can show me how to set up a UICollectionView without having to use Storyboards or XIB/NIB files - but unfortunately when I search about, all I can find is tutorials that feature the Storyboard.

推荐答案

头文件:--

@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    UICollectionView *_collectionView;
}

实施文件:--

- (void)viewDidLoad
{
     [super viewDidLoad];
     self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

     UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    _collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    [_collectionView setDataSource:self];
    [_collectionView setDelegate:self];

    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
    [_collectionView setBackgroundColor:[UIColor redColor]];

    [self.view addSubview:_collectionView];


    // Do any additional setup after loading the view, typically from a nib.
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 15;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor=[UIColor greenColor];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(50, 50);
}

输出---

这篇关于以编程方式创建 UICollectionView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆