[英]cell of collection view not displaying in row
我有12张图片,我想在UICollectionView
显示此图片, UICollectionView
包含4行,每行包含3张图片。
这是我的.h文件代码
@interface MyMusic : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
{
UICollectionView *_collectionView;
}
@end
这是我的.m文件代码
- (void)viewDidLoad{
enter code hereUICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(100, 100)];
[flowLayout setMinimumLineSpacing:5];
[flowLayout setMinimumInteritemSpacing:5];
[flowLayout setSectionInset:UIEdgeInsetsMake(0, 0, 0, 0)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10,238, 300, 200) collectionViewLayout:flowLayout];
_collectionView.backgroundColor = [UIColor redColor];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[self.view addSubview:_collectionView];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 4;}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{return 3;}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
enter UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
cell.backgroundColor=[UIColor greenColor];
return cell;
}
上面的代码工作正常,但我的输出将无法正常显示
它看起来像这样
任何人都可以帮助我如何解决这个问题?
您的UICollectionView
宽度为300 UICollectionView
,项目的宽度为100 UICollectionView
。 中间空间是5点,所以
100*3 + 5*2 = 310.
这就是为什么您仅看到2列的原因。
使您的单元格的宽度稍小一些,例如290
或将中间间距设置为0。
主要规则-您的UICollecitionView
宽度应大于或等于单元格widths + interitem spacing
总和widths + interitem spacing
更换
[flowLayout setItemSize:CGSizeMake(100, 100)];
通过
[flowLayout setItemSize:CGSizeMake(75,100 )];
我仅将75用于试用目的,并考虑使用iPhone屏幕。因此,列宽相等。
但是,您不应使用硬编码的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.