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 

지금에도이 함수를 필요로하지 않는다 collectionViewCell이 아직 보이지 않는 경우 호출됩니다.이 경우 이미지는 cellForItemAtIndexPath 메소드에 설정되어 있기 때문입니다.

내 질문에, 어떻게 우리가 다루고있는 셀이 현재 보이는지 아닌지를 확인하기 위해이 함수를 어떻게 바꿀 수 있습니까? 나는 collectionView.visibleCells()을 알고 있지만, 여기에 적용하는 방법을 모르겠습니다.

답변

7

visibleIndexPaths을 표시하려면 followedCollectionView.indexPathsForVisibleItems()을 사용하고 에는 indexPath이 포함되어 있는지 확인한 다음 셀을 사용하여 수행하십시오.

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는 모든 셀을 항상 볼 수있는 것으로 인식합니다. 이 경우 화면 경계를 기준으로 취할 수 있습니다.

let cellRect = cell.contentView.convert(cell.contentView.bounds, to: UIScreen.main.coordinateSpace) 
    if UIScreen.main.bounds.intersects(cellRect) { 
     print("cell is visible") 
    } 
관련 문제