[英]Cells in UICollectionView are overlapping
我正在使用一个ViewController,我用这种方式添加一个UICollectionView:
UICollectionViewFlowLayout *collectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[collectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[collectionViewFlowLayout setMinimumInteritemSpacing:2];
[collectionViewFlowLayout setMinimumLineSpacing:4];
[collectionViewFlowLayout setHeaderReferenceSize:CGSizeMake(320, 30)];
CGRect collectionViewFrame = self.view.bounds;
self.collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:collectionViewFlowLayout];
self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
[self.collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:myCellIdentifier];
[self.view addSubview:self.collectionView];
这就是我正在初始化我的自定义单元格对象的方式(我确保每个单元格的框架填满整个屏幕宽度,以便在UICollectionView中垂直渲染单元格):
CGSize mySize = CGSizeMake(320, 158);
self.myTitle = [[UILabel alloc ] initWithFrame:CGRectMake(0, 0, mySize.width, mySize.height)];
[self.myTitle setTextColor:[UIColor whiteColor]];
[self.myTitle setBackgroundColor:[UIColor greenColor]];
[self.myTitle setTextAlignment:NSTextAlignmentLeft];
[self.myTitle setNumberOfLines:1];
[self.myTitle setText:@"My Title"];
[self addSubview:self.myTitle];
这是我在initWithNibName中初始化单元格框架的方法:
CGSize mySize = CGSizeMake(320, 158);
self = [super initWithFrame:CGRectMake(0, 0, mySize.width, mySize.height)];
这是我的cellForItemAtIndexPath代码:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:myCellIdentifier forIndexPath:indexPath];
return cell;
}
现在我有四个这样的细胞,但它们是重叠的。 我究竟做错了什么? 谢谢!
实现UICollectionViewFlowLayout委托调用:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(320, 158);
}
或者由于所有大小都是常量,只需在Flow布局中指定大小,如下所示:
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.itemSize = CGSizeMake(320, 158);
在numberOfSectionsInCollectionView中:方法使用
[self.collectionView.collectionViewLayout invalidateLayout];
我希望它会奏效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.