UICollectionView仅显示第一项 [英] UICollectionView shows only the first item
问题描述
我正在从事类似于视频专辑的项目.在这种情况下,我使用UICollectionView
来显示这些视频的缩略图.最糟糕的是我不应该使用情节提要或Xib文件.我试图以编程方式执行此操作.我目前正在处理此代码:
I'm working on a project similar to a video album. In that I'm using UICollectionView
to display the thumb images of those videos. The worst part is that I should not use storyboard or xib files. I have tried to do this programatically. I'm currently working on this code:
- (void)viewDidLoad
{
i = 0;
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
[layout setItemSize:CGSizeMake(self.view.frame.size.width/2.5,self.view.frame.size.width/2.5)];
collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[collectionView setDataSource:self];
[collectionView setDelegate:self];
collectionView.backgroundColor = [UIColor whiteColor];
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"MyCell"];
[self.view addSubview:collectionView];
[super viewDidLoad];
}
我在numberOfSectionsInCollectionView
中给了1作为回报,在numberOfItemsInSection
中给了[myArray count]
作为回报.
I have given 1 for return in numberOfSectionsInCollectionView
and [myArray count]
for return in numberOfItemsInSection
.
-(UICollectionViewCell *) collectionView:(UICollectionView *)cV cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [cV dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor blackColor];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.frame.origin.x , cell.frame.origin.y, cell.frame.size.width, (cell.frame.size.height - cell.frame.size.height/3))];
cell.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.frame.origin.x , cell.frame.origin.y, cell.frame.size.width, (cell.frame.size.height - cell.frame.size.height/3))];
imageView.image = [UIImage imageNamed:[storeData objectAtIndex:i]];
[cell addSubview:imageView];
i++;
return cell;
}
我已经重新检查了myArray
中的图像.加载视图时,集合视图仅显示第一张图像.其他4个单元为空.我的代码有什么问题?
I have rechecked the images in myArray
. When the view loads, the collection view shows only the first image. Other 4 cells are empty. What is wrong with my code?
推荐答案
对于遇到此问题的用户,frame
是关键.我遇到了这个问题并更改了:
For those who is experiencing this problem, frame
is the key. I've encountered this and changed:
cell.imageView.frame = cell.frame;
进入
cell.imageView.frame = cell.bounds;
操作正在使用:
cell.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.frame.origin.x , cell.frame.origin.y, cell.frame.size.width, (cell.frame.size.height - cell.frame.size.height/3))];
这就是为什么发生这种情况.
That's why this happened.
这篇关于UICollectionView仅显示第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!