iosswiftuicollectionviewnsindexpath

How can I check if an indexPath is valid, thus avoiding an "attempt to scroll to invalid index path" error?


How can I check to see whether an indexPath is valid or not?

I want to scroll to an indexPath, but I sometimes get an error if my UICollectionView subviews aren't finished loading.


Solution

  • You could check

    - numberOfSections
    - numberOfItemsInSection: 
    

    of your UICollection​View​Data​Source to see if your indexPath is a valid one.

    E.g.

    extension UICollectionView {
    
        func isValid(indexPath: IndexPath) -> Bool {
            guard indexPath.section < numberOfSections,
                  indexPath.row < numberOfItems(inSection: indexPath.section)
                else { return false }
            return true
        }
    
    }