以编程方式创建UICollectionView [英] Creating a UICollectionView programmatically
本文介绍了以编程方式创建UICollectionView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一个指南或教程,它将告诉我如何只使用代码设置一个简单的UICollectionView。
Im looking for a guide or tutorial that will show me how to set up a simple UICollectionView using only code.
Im通过 Apples网站上的文档和Im使用参考手册。
Im wading through the documentation on Apples site, and Im using the reference manual as well.
但我真的可以从一个简单的指南中获益,它可以告诉我如何设置一个UICollectionView,而不必使用Storyboards或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屋!
查看全文