Dmitriy Babinskiy Dmitriy Babinskiy - 2 months ago 7
Objective-C Question

How to set two image view for CollectionViewCell

I have an

ImagePickerController
for photo and video. When I pick photo or video from camera I display it in a
CollectionView
as image. At this step everything works. I add a
Bool
variable
checkVideo
to know what image I have in cell, image from video or photo.
checkVideo
change value when I use imagePickerController for video or photo. I want to add a new image with the play icon for images which comes from video. Here is my code :

- (CustomCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];

if (checkVideo == YES) {

UIImageView *playVideoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
playVideoImageView.image = playImg;
[cell addSubview:playVideoImageView];
cell.imageViewCell.image = arrayForImages[indexPath.row];
checkVideo = NO;
} else {
cell.imageViewCell.image = arrayForImages[indexPath.row];
}
NSLog(@"check video %@", checkVideo ? @"YES" : @"NO");
return cell;
}

Answer

You may need to make two prototypes, instead of one: MyCell1 and MyCell2 in your storyboard's collectionView Scene, then:

- (CustomCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell1" forIndexPath:indexPath];

    // previously, you were using the same variable, that always had the same value for each row... 
    // you should grab a value from your prepared array like this:

    Bool checkVideo = checkVideoArray[indexPath.row]

    if (checkVideo == YES) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell2" forIndexPath:indexPath];        
        cell.imageViewCell.image = arrayForImages[indexPath.row];

        // in your prototype MyCell2 you now have to add one more subView like 'playImageView'
        // don't forget to link it via @IBOutlet too
        // reuse handling will be safe here - because if you were adding subview each time in cellForRow method, the image wouldn't be handled properly and it would be re-adding a layer on layer, what wouldn't be OK
        cell.playImageView.image = playImg;                         
    } else {
        cell.imageViewCell.image = arrayForImages[indexPath.row];
    }
    NSLog(@"check video %@", checkVideo ? @"YES" : @"NO");
    return cell;
}