UICollectionViewController 以编程方式因非零布局参数错误而崩溃 [英] UICollectionViewController Programmatically crashing with non-nil layout parameter error

查看:11
本文介绍了UICollectionViewController 以编程方式因非零布局参数错误而崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以编程方式创建 UICollectionViewController.不,我不想像每个教程一样使用 IB 和 Storyboard.我只想使用纯代码.

I am creating a UICollectionViewController programmatically. No, I don't want to use IB and Storyboards like every tutorial out there. I just want to use plain code.

这是我的 viewDidLoad 中的内容:

Here is what I have in my viewDidLoad:

// UICollectionView
    UICollectionViewFlowLayout *aFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    [aFlowLayout setItemSize:CGSizeMake(200, 140)];
    [aFlowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:aFlowLayout];
    [self.collectionView setDelegate:self];
    [self.collectionView setDataSource:self];
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth];
    [self.collectionView registerClass:[PUCImageGridCell class] forCellWithReuseIdentifier:CollectionViewCellIdentifier];

我已经实现了所需的委托方法,但我仍然收到此错误:

I have implemented the required delegate methods and I still get this error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'UICollectionView must be initialized with a non-nil layout parameter'

推荐答案

这是我用来初始化一个 UICollectionViewController:

This is what I use to initialize a UICollectionViewController:

- (id)initWithCollectionViewLayout:(UICollectionViewLayout *)layout

您不需要实例化collectionView,控制器会为您完成.在调用它之后设置框架,或者您可以覆盖并设置内部框架:

You do not need to instantiate the collectionView the controller will do it for you. Set the frame after calling this or you can override and set the frame inside:

- (id)initWithCollectionViewLayout:(UICollectionViewLayout *)layout{
     self = [super initWithCollectionViewLayout:layout];
     if (self) {
         // additional setup here if required.
     }
     return self;
}

我更喜欢使用 自动布局 约束.

I prefer to use the autolayout constraints.

这篇关于UICollectionViewController 以编程方式因非零布局参数错误而崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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