且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UICollectionView:必须用非零布局参数初始化

更新时间:2022-06-17 21:47:26

崩溃非常明确地告诉你出了什么问题:

The crash is telling you pretty explicitly what is going wrong:

UICollectionView 必须使用非零布局参数初始化.

UICollectionView must be initialized with a non-nil layout parameter.

如果您检查 UICollectionView 的文档,你会发现唯一的初始化器是 initWithFrame:collectionViewLayout:.此外,在该初始化程序的参数中,您会看到:

If you check the documentation for UICollectionView, you'll find that the only initializer is initWithFrame:collectionViewLayout:. Further, in the parameters for that initializer, you'll see:

框架

集合视图的框架矩形,以磅为单位.框架的原点是相对于您计划在其中添加它的超级视图.此帧在初始化期间传递给超类.

The frame rectangle for the collection view, measured in points. The origin of the frame is relative to the superview in which you plan to add it. This frame is passed to the superclass during initialization.

布局

用于组织项目的布局对象.集合视图存储对指定对象的强引用.不能为零.

The layout object to use for organizing items. The collection view stores a strong reference to the specified object. Must not be nil.

我已经加粗了重要的部分.您必须使用 initWithFrame:collectionViewLayout: 来初始化您的 UICollectionView,并且您必须向其传递一个非 nil UICollectionViewLayout 对象.

I've bolded the important part. You must use initWithFrame:collectionViewLayout: to initialize your UICollectionView, and you must pass it a non-nil UICollectionViewLayout object.

因此,解决此问题的一种方法是简单地更改您执行的初始化顺序:

One way to fix this, then, would be to simply change the order of initialization you do:

UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.itemSize = CGSizeMake(100, 100);
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];

请注意,在上面的示例中,我假设您想使用 self.view.frame 作为 self.collectionView 的框架.如果不是这种情况,请插入您想要的任何框架.

Note that in the above example, I've assumed you want to use self.view.frame as the frame of self.collectionView. If that's not the case, insert whatever frame you want instead.