我有一个简短的问题。我想以编程方式创建一个具有UICollectionView的ViewController,并将其添加到ScrollView。如果我使用Interfacebuilder进行此操作,一切正常。但是创建一个实例并以编程方式添加它并不起作用,CollectionView也不会出现。这是我的代码的一部分:
ViewController.m
ViewControllerCell* Cell = [[ViewControllerCell alloc]init];
[_contentScrollView addSubview:Cell.view];
ViewControllerCell.m
- (void)viewDidLoad{
[super viewDidLoad];
[self.view addSubview:self.collectionView];
[self.view setBackgroundColor:[UIColor lightGrayColor]];
}
浅灰色背景确实出现了,所以我认为,子视图已添加,但不知何故我的收藏视图不会出现。有人可以帮帮我吗?
答案 0 :(得分:1)
检查您是否正确添加委托方法
@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
UICollectionView *_collectionView;
}
- (void)viewDidLoad {
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
_collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:_collectionView];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 10;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
cell.backgroundColor=[UIColor blueColor];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(40, 40);
}