簡體   English   中英

UICollectionView + SDWebImage + 單元重用

[英]UICollectionView + SDWebImage + Cell reuse

我有一個帶有自定義 UICollectionViewCell class 的 UICollectionView,它將另一個 UIView (thumbnailView) 添加到它的 contentView。 另一個視圖有一個 UIImageView 屬性 (imageView),其圖像通過 SDWebImage 異步加載。 這一切工作正常,直到單元格被重新使用,而原始單元格的圖像仍在加載。 如果您在 CollectionView 中滾動得足夠快,圖像開始在它們不應該出現的單元格中彈出(可能是因為單元格被重復使用並且圖像下載隨后完成),只是為了重新使用的正確圖像盡快被替換單元格完成加載。

為了解決這個問題,我將以下內容添加到我的 UICollectionViewCell 子類中以停止原始單元格的圖像下載:

- (void)prepareForReuse
{
    [super prepareForReuse];
    [self.thumbnailView.imageView cancelCurrentImageLoad];
}

但令我驚訝的是,這似乎完全沒有改變。 我做錯了什么還是我只是看錯了方向?

如果我正確理解了您的問題,那么您仍然會在重復使用的單元格中顯示舊圖像,因此除了停止先前的圖像加載之外,您可能還想從imageView中刪除舊圖像。 SDImageView可能有清除圖像的方法,否則您只需用占位符圖像手動替換它。

- (void)prepareForReuse
{
    [super prepareForReuse];
    [self.thumbnailView.imageView cancelCurrentImageLoad];
    [self.thumbnailView.imageView setImage:<<LOCAL PLACEHOLDER IMAGE>> forState:UIControlStateNormal];
}

UITableViewDelegateUICollectionViewDelegate方法-tableView:didEndDisplayingCell:forRowAtIndexPath:是更新UITableView的最佳位置。 UICollectionView單元格消失后。 您可以在那里取消單元格下載。

Swift 4 - 添加到您的手機類:

override func prepareForReuse() {
  super.prepareForReuse() 
  self.contentImageView.sd_cancelCurrentImageLoad()
  self.contentImageView.image = UIImage(named: "") // set to default/placeholder image
}

我嘗試了didEndDisplayCell()和prepareForReuse(),它們都不起作用。 一種工作方式是將imageView.image設置為nil然后分配給特定圖像,然后它不會將舊圖像作為背景閃爍。 (但它會慢一點,因為它必須先做“干凈”的工作)。

SWIFT 4

在將新圖像設置為imageView之前添加:

cell.imageView.sd_currentDownloadTask?.cancel()

最終,我通過以編程方式使用 static 單元並通過 SDWebImage 單獨下載圖像來解決問題,嘗試從另一個管理器的緩存中處理圖像。

這是 SDWebImage 代碼。

 [imageView sd_internalSetImageWithURL:url placeholderImage:nil options:SDWebImageRetryFailed context:nil setImageBlock:^(UIImage * _Nullable image, NSData * _Nullable imageData, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
    
 } progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
    
 } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
    
    if (image) { imageView.image = image; }
    
 }];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM