0

我有一个UICollectionView其中包含一个UIImageView,只有一行。我试图在点击时将图像更改为选定图像,但由于某些原因图像不会更新。当UICollectionView调用的UIImage设置:如何更改UICollection UIImageView中的UImage?

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 

,但是当它调用它不会更新:

  • (无效)的CollectionView:(UICollectionView *)的CollectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

这里是代码,你可以看到我已经尝试过setNeedsDisplay,reloadData,setImage和UImageView自身,而不是在cellForItemAtIndexPath中设置它...没有任何工作。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 

    UICollectionViewCell *cell; 
    UIImage *curImage; 

    static NSString *cellAvatarMediaIdentifier = @"cvAvatarCell"; 


    cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellAvatarMediaIdentifier forIndexPath:indexPath]; 

    Child *currentChild = [self.children objectAtIndex:indexPath.row]; 

    curImage = [UIImage imageNamed:@"male.png"]; 

    UIImageView *childSilhouetteView = (UIImageView *)[cell viewWithTag:300]; 

    if (curImage != nil) 
    { 
     // this WORKS !!!! 
     [childSilhouetteView setImage:curImage]; 
    } 

    return cell; 
} 

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
     UIImage *selectedImage; 

     Child *currentChild = [self.children objectAtIndex:indexPath.row]; 

     UIImageView *childSilhouetteView = (UIImageView *)[collectionView viewWithTag:300]; 

     selectedImage = [UIImage imageNamed:@"male_selected.png"]; 

     if (selectedImage != nil) 
     { 
       // This does NOT work, image is never updated 
       NSLog(@"Before setting image"); 
       childSilhouetteView = nil; 

       [childSilhouetteView setImage:selectedImage]; 
       [childSilhouetteView setNeedsDisplay]; 
       [collectionView reloadData]; 
     } 
} 

回答

0

您还需要找到相应的孩子didSelectItemAtIndexPath:,目前您访问的是collectionView的与标签视图。

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
     UIImage *selectedImage; 

     Child *currentChild = [self.children objectAtIndex:indexPath.row]; 

     UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; 

     UIImageView *childSilhouetteView = (UIImageView *)[cell viewWithTag:300]; 

     selectedImage = [UIImage imageNamed:@"male_selected.png"]; 

     if (selectedImage != nil) 
     { 
       // This does NOT work, image is never updated 
       NSLog(@"Before setting image"); 
       // childSilhouetteView = nil; 

       [childSilhouetteView setImage:selectedImage]; 
       [childSilhouetteView setNeedsDisplay]; 
       // [collectionView reloadData]; 
     } 
} 

如果你打电话reloadData,您的CollectionView将被重绘,所以你会看到你的意见的默认图像。

0

首先要访问特定单元格的项目,首先需要获取单元格。

检查这个答案: UICollectionView didSelectRowAtIndexPath doesn't work

其次确保编译器进入你在哪里查看图像的条件是零或不是。确保资产文件夹中的“male_selected.png”存在同名。

第三步是删除所有不必要的代码。你很好去