UICollectionView 仅显示第一项 [英] UICollectionView shows only the first item

查看:19
本文介绍了UICollectionView 仅显示第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个类似于视频专辑的项目.我正在使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆