1

我正在使用xcode 8.3。我有一個CollectionView。我已經從網絡服務下載圖像,並將圖像放置在每個CollectionView單元格中。但是當我滾動CollectionView時,每個單元格中的圖像都在改變。幾分鐘後,它顯示正確的圖像。我已經嘗試了很多可用的解決方案。但我沒有得到解決方案。請幫幫我。滾動時,collectionView中的圖像正在更改

+0

請修改您的問題以包括您編寫的用於從Web服務加載圖像的代碼,以及您爲寫入圖像而編寫的代碼。 –

+0

嘗試使用sdwebimage進行圖像下載.. – KKRocks

回答

1

這是因爲重複使用單元格。嘗試重置您的單元格類中的圖像prepareForReuse方法

-(void)prepareForReuse { 
    [super prepareForReuse]; 
    self.imageView.image = nil; 
} 
1

您面臨的問題是由於UITableViewCell的重用。 如果您使用網絡服務使用AlamofireImageSDWebImage下載圖像。它會處理你的問題。

3

與其他人一樣,最有可能的原因是您將可重用細胞出列(如您所願)並將cell.imageView.image屬性設置爲您的Web圖像。

這裏的問題是,因爲iOS通過「重複使用」這些單元來節省內存,它們實際上是內存中的相同單元。所以它滾動屏幕的一個邊緣並消失。當新的單元格滾動而不是創建一個新的單元格時,它只是使用剛剛離開屏幕的單元格。這意味着您的舊圖像仍然是單元格中顯示的圖像。

標準做法是在cellForRowAtIndexPath:方法中設置單元格的內容。但是,如果將它設置爲異步提取的圖像,則在獲取新圖像之前,完全可能(有可能)單元出現在舊圖像的屏幕上。據推測,一旦圖像下載不再是一個問題了,因爲它們應該立即從緩存中返回。

這裏的簡單解決方法是在將圖像設置爲每次在單元格中之前將圖像設爲零,或者最好使用佔位符圖像。

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

    // This will clear any existing image from the cell about to be displayed it is an option 
    //[cell.imageView setImage:nil]; 

    if (ImageExistsLocally) 
    { 
     cell.imageView.image = [UIImage imageWithContentsOfFile:@"SomeImagePath"]; 
    } 
    else 
    { 
     [cell.cellImageView sd_setImageWithURL:yourRemoteImage.thumbnailUrl 
           placeholderImage:[UIImage imageNamed:PlaceHolderImageName] 
            completed:nil]; 
    } 
    return cell; 
} 

請注意sd_setImageWithURL來自SDWebImage庫,我認爲別人在這裏提到過。 https://cocoapods.org/pods/SDWebImage

0

UICollectionView重複使用相同的UICollectionViewCell以提高性能。只有UICollectionViewCell內的數據發生更改,因此在使用UICollectionViewCell之前,必須清除UICollectionViewCell的先前數據。 Cocoa Framework提供了一種在UICollectionViewCell中存在的方法,每當UICollectionViewCell要被重新使用時觸發。

只覆蓋您的自定義UICollectionViewCell類文件的.m文件

-(void)prepareForReuse { 
    [super prepareForReuse]; 
// here we clear the previously set data 
    self.imageView.image = nil; // this will clear the previously set imageView is a property of UIImageView used to display a image data 
} 
0

您可以使用prepareForReuse()的方法來處理這個問題,下面給出的函數。

override func prepareForReuse() { 
    super.prepareForReuse() 

    // still visible on screen (window's view hierarchy) 
    if self.window != nil { return } 

    imageView.image = nil 
} 

注:如果您正在使用SDWebImage,你應該加入這一行取消當前單元格的圖像下載。

imageView.sd_cancelCurrentAnimationImagesLoad()