Lücks
Lücks

Reputation: 3994

iOS: CollectionView with image error

I created a Collection View on my View, and now I'm trying to insert a image on the cell: But, the screen stay black. I saw that the code: UIImageView *imageView = (UIImageView *)[cell viewWithTag:100]; is returning nil. What is the problem?

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath; {
    static NSString *identifier = @"Cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    UIImageView *imageView = (UIImageView *)[cell viewWithTag:100];
    imageView.image = [UIImage imageNamed:@"ic_see_on_map.png"];

    return cell;

     }

Upvotes: 0

Views: 654

Answers (2)

Shivam Mishra
Shivam Mishra

Reputation: 137

Why don't you extract cell using cellForItemAtIndexPath and then traverse its hierarchy for imageview. Using tags is not advised as multiple cell's image views will get the same tag value which renders viewWithTag useless. Secondly you said screen stays black, are you able to see any cells of collection view or not? because than it means your collection view itself is not getting instantiated. To reset tag is to go to nib and set tag property to 0.

Upvotes: 1

chancyWu
chancyWu

Reputation: 14413

You set the UICollectionViewCell and UIImageView' tags to 100 in your cell XIB. then UIImageView *imageView = (UIImageView *)[cell viewWithTag:100]; will return the UICollectionViewCell. Then you cast a UICollectionViewCell object to UIImageView object. that's the problem. You need reset the UICollectionViewCell's tag to 0 or whatever not 100. Then you can get the UIImageView with tag 100.

Upvotes: 1

Related Questions