1

Follow this answer on SO I be able to create UICollectionView programmatically. But I can't find any better solution when I try to add subview into UICollectionViewCell. Here is how most answer on SO achieve

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,100,100)];
    image.image = /*some image*/
    [cell addSubview:image];
    return cell;
}

Maybe i'm wrong but the purpose of using UICollectionView wasn't because of recycle and reuse to optimize the performance? If using the code above when the user scrolling wasn't it add more and more UIImageView into UICollectionViewCell subview when dequeueReusableCellWithReuseIdentifier get trigger?

So what is the better way to do this? I can't use UITableView for this because I need the horizontal scrolling technique.

NOTE: I need to create it programmatically without using xib.

Community
  • 1
  • 1
teck wei
  • 1,275
  • 9
  • 21

1 Answers1

1

Yes, It will add imageView everytime when your collection view will get scrolled! And it is not good approach. Now, what you can do is, Take one image view in your collectionview cell, I mean in interface builder(xib or storyboard whatever you have used) and in cellForItemAtIndexPath just show or hide that image view as per need or change image of it as per requirement!

Update :

If you have create collection view programmatically then you can set some flag in your cellForItemAtIndexPath! Take one flag and set it after adding imageview. and you can declare imageview and flag as global variable. Something like,

   if (!isImageAdded) {

    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,100,100)];
    imageView.image = /*some image*/
    [cell addSubview:image];
    isImageAdded = YES;
}
else{

    imageView.image = /*some image*/
}
Ketan Parmar
  • 25,426
  • 9
  • 43
  • 67