簡體   English   中英

檢測iOS UICollectionCell何時離開屏幕

[英]detecting when an iOS UICollectionCell is going off screen

我有一個UICollectionView ,它將圖片保存為數據存儲區中的元素。

我想只在其對應的UICollectionViewCell當前顯示在屏幕上時才將高分辨率pic加載到元素中。 之后,當UICollectionViewCell關閉屏幕時,我想將元素的UIImage返回到低分辨率版本。

我的問題是,如何檢測UICollectionViewCell何時離開屏幕?

(我嘗試使用prepareForReuse方法但我無法預測何時會調用它)。

我目前正在使用一段位於scrollViewDidScroll的代碼,每次視圖滾動時我都會檢查self.collectionView.visibleCells以查看哪些單元格已在屏幕上滾動。

這似乎有點開銷,我想知道在滾動屏幕時是否有一個UICollectionViewCell本身調用的方法?

collectionView:didEndDisplayingCell:forItemAtIndexPath:在方法UICollectionViewDelegate應該做你想要什么。

來自文檔。 collectionView:didEndDisplayingCell在完成顯示后立即調用,而不是在它離開屏幕時調用

使用此方法可以檢測何時從集合視圖中刪除單元格,而不是監視視圖本身以查看它何時消失

collectionView:didEndDisplayingCell:forItemAtIndexPath:是檢測單元格何時離開屏幕的正確方法。

同時,我認為不在 collectionView:didEndDisplayingCell:forItemAtIndexPath:執行清理更為正確collectionView:didEndDisplayingCell:forItemAtIndexPath:但要告訴您的單元格自己執行清理:

  func collectionView(_ collectionView: UICollectionView,
                 didEndDisplaying cell: UICollectionViewCell,
                   forItemAt indexPath: IndexPath) {
    cell.prepareForReuse()
  }

使用這種方法,您的UICollectionViewDelegate不必知道您的UICollectionViewCell子類的任何實現細節。 在單元格中,我們將覆蓋prepareForReuse方法:

 override func prepareForReuse() {
    super.prepareForReuse()

    imageView.image = lowResolutionImage
    highResolutionImage = nil
 }

暫無
暫無

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

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