UICollectionViewController不同於其他viewcontroller,在使用過程中特別容易出現這種錯誤
UICollectionView must be initialized with a non-nil layout parameter
如果是這樣(已經建立了一個UICollectionViewController的storyboard),這是因爲你還沒有關聯上storyboard。
以下是國外一個論壇上面的解釋:
- (id)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout
So you need to pass it a layout object. You don't show the code where you make a collection view, but I'm assuming CollectionViewController
is
a UICollectionViewController
subclass,
in which case you need to use this designated initialiser:
- (id)initWithCollectionViewLayout:(UICollectionViewLayout *)layout
Currently, you're using init
.
In both cases you need to create and pass in a layout object when initalising.
If your collection view is held in the storyboard then you need to get it from the storyboard using instantiateViewControllerWithIdentifier:
,
so your code above would read something like:
viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"CollectionViewController"];
另外在使用UICollectionViewCell的時候自動會生成
static NSString * const reuseIdentifier = @"Cell";這個變量註冊時候無需更改,只在要使用的時候使用自定義標識即可。