我正在以编程方式创建一个UICollectionViewController.不,我不想像每个教程那样使用IB和Storyboard.我只想使用普通代码.
这是我在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];
Terminating app due to uncaught exception 'NSInvalidArgumentException',reason: 'UICollectionView must be initialized with a non-nil layout parameter'
解决方法
这是我用来初始化
UICollectionViewController:
- (id)initWithCollectionViewLayout:(UICollectionViewLayout *)layout
您不需要实例化集合视图,控制器将为您执行此操作.调用此框后设置框架,或者您可以覆盖并设置内部框架:
- (id)initWithCollectionViewLayout:(UICollectionViewLayout *)layout{ self = [super initWithCollectionViewLayout:layout]; if (self) { // additional setup here if required. } return self; }
我更喜欢使用autolayout约束.