我以编程方式设置了一个集合视图:
我合成了 2 个属性:
@property (strong) IconCollectionViewController *collectionViewController;
@property (strong) UICollectionView *collectionView;
然后 :
// Create a layout for the collection view
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
// Create the collection view
self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"IconCell"];
// Create a collection view controller, and link it with the collection view
self.collectionViewController = [[IconCollectionViewController alloc] initWithCollectionViewLayout:flowLayout];
self.collectionView.delegate = self.collectionViewController;
self.collectionView.dataSource = self.collectionViewController;
self.collectionViewController.collectionView = self.collectionView;
此外,集合视图控制器实现了所需的协议:
@interface IconCollectionViewController () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
如果我将集合视图呈现为子视图,则一切正常:
[self.view addSubview:collectionView];
但是我不能使用新设置的集合视图控制器来展示它:
[self presentViewController:self.collectionViewController animated:YES completion:nil];
在这种情况下,我收到错误消息
*** Assertion failure in -[UICollectionView
_dequeueReusableViewOfKind:withIdentifier:forIndexPath:],
/SourceCache/UIKit_Sim/UIKit-2380.17/UICollectionView.m:2249
当我尝试使单元格出队时,在数据源回调中
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"IconCell" forIndexPath:indexPath];
return cell;
}
有人可以解释为什么将集合视图呈现为子视图有效,并在单元格应该出列时使用集合视图控制器呈现它失败?谢谢你的帮助。