UICollectionView показывает только первый элемент
Я работаю над проектом, похожим на видеоальбом. Во что я использую UICollectionView
для отображения большого пальца изображения этих видео. Хуже всего то, что я не должен использовать раскадровку или файлы XIB. Я пытался сделать это программно. В настоящее время я работаю над этим кодом:
- (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];
}
Я дал 1 для возвращения в numberOfSectionsInCollectionView
а также [myArray count]
для возвращения в 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 ячейки пусты. Что не так с моим кодом?
4 ответа
Для тех, кто испытывает эту проблему, frame
это ключ. Я столкнулся с этим и изменил:
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))];
Вот почему это произошло.
Вы не должны использовать i
в качестве счетчика. Весь смысл метода делегата, посылающего вам indexPath
является то, что он говорит вам, какую информацию получить из вашего массива исходных данных. Итак, удалите i
и использовать indexPath.row
вместо.
Вам также не нужно 2 просмотра изображений. Но вам, вероятно, следует сохранить свое специальное подпредставление и не использовать ячейки, встроенные в представление изображений.
Вам не нужен счетчик. Как указано Wain, используйте indexPath.row
,
Важно отметить, что вы не должны создавать новые подпредставления в cellForItemAtIndexPath
, а лучше использовать этот метод, чтобы заполнить их соответствующим образом с содержанием. Вы можете поместить изображения в ячейки прототипа раскадровки и идентифицировать их по тегам. Каждая клетка вернулась из dequeueReusableCellWithReuseIdentifier
будет уже содержать представление изображения.
Вы никогда не должны создавать элементы пользовательского интерфейса в cellForRowAtIndexPath:
, Подкласс ячейки представления коллекции выглядит так:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSLog(@"INIT WITH FRAME FOR CELL");
//we create the UIImageView here
imageView = [[UIImageView alloc] init];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.frame = CGRectMake(cell.frame.origin.x , cell.frame.origin.y, cell.frame.size.width, (cell.frame.size.height - cell.frame.size.height/3));
[self.contentView addSubview:imageView]; //the only place we want to do this addSubview: is here!
}
return self;
}
Затем добавьте эту ячейку в качестве свойства и измените этот код:]
[collectionView registerClass:[customCellClass class] forCellWithReuseIdentifier:@"MyCell"];
Выполните эти изменения:
-(customCellClass *) collectionView:(UICollectionView *)cV cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = (customCellClass *)[cV dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor blackColor];
imageView.image = [UIImage imageNamed:[storeData objectAtIndex:indexPath.row]];
return cell;
}
Окончательная корректировка будет состоять в том, чтобы переместить [super viewDidLoad]
к этому:
- (void)viewDidLoad
{
[super viewDidLoad];
//insert the rest of the code here rather than before viewDidLoad
}