3

私はCollectionViewを持っています。これらをバックグラウンドでダウンロードし、ダウンロードが完了したら、次のfuncを呼び出してcollectionViewCellを更新し、画像を表示します。indexPathのセルが画面上に表示されているかどうか確認してください。UICollectionView

func handlePhotoDownloadCompletion(notification : NSNotification) { 
    let userInfo:Dictionary<String,String!> = notification.userInfo as! Dictionary<String,String!> 
    let id = userInfo["id"] 
    let index = users_cities.indexOf({$0.id == id}) 
    if index != nil { 
     let indexPath = NSIndexPath(forRow: index!, inSection: 0) 
     let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as! FeaturedCitiesCollectionViewCell 
     if (users_cities[index!].image != nil) { 
      cell.backgroundImageView.image = users_cities[index!].image! 
     } 
    } 
} 

セルが画面上に現在表示されている場合、これは素晴らしい作品、それがない場合はしかし、私は次の行に fatal error: unexpectedly found nil while unwrapping an Optional valueエラーが出る:

let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as! FeaturedCitiesCollectionViewCell 

今、この機能もする必要はありませんがこの場合、画像はcellForItemAtIndexPathメソッドで設定されるため、collectionViewCellがまだ表示されていない場合に呼び出されます。

私の質問ですが、私が扱っているセルが現在表示されているかどうかを調べるためにこの関数を変更するにはどうすればよいですか?私はcollectionView.visibleCells()を知っていますが、ここでそれをどのように適用するかはわかりません。可視セルvisibleIndexPathsを取得し、細胞を用いて何かを行う前に、あなたのindexPathvisibleIndexPathsに含まれる、またはされていませんチェックするfollowedCollectionView.indexPathsForVisibleItems()を使用し

答えて

1

if collectionView.cellForItem(at: indexPath) == nil { }をそのまま使用できます。 collectionViewは、表示されている場合にのみセルを返します。

またはあなたの場合

は、特に変更:

if let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as? FeaturedCitiesCollectionViewCell { }

0

ネストされたUICollectionViewsは何contentOffsetがこれまで提供されていないように、すべてでスクロールしないためにしばしば必要とので:

let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as! FeaturedCitiesCollectionViewCell

にiOSは、すべてのセルが常に可視であると理解しています。この場合、画面の境界線を基準として取ることが可能です:

関連する問題