Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 563
webmagnets Avatar asked Apr 08 '15 13:04

webmagnets


People also ask

What is IndexPath in tableView Swift?

indexPath(for:)Returns an index path that represents the row and section of a specified table-view cell.

How do I get IndexPath from cell Swift?

add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.

How does Swift compare to IndexPath?

The Swift overlay to the Foundation framework provides the IndexPath structure, which bridges to the NSIndexPath class. This means that, as an alternative to NSIndexPath , starting with Swift 3 and Xcode 8, you can use IndexPath . Note that IndexPath also conforms to Equatable protocol. Therefore, you can use == or !=


2 Answers

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     }  } 
like image 97
muffe Avatar answered Sep 19 '22 14:09

muffe


A more concise solution?

func indexPathIsValid(indexPath: NSIndexPath) -> Bool {     if indexPath.section >= numberOfSectionsInCollectionView(collectionView) {         return false     }     if indexPath.row >= collectionView.numberOfItemsInSection(indexPath.section) {         return false     }     return true } 

or more compact, but less readable...

func indexPathIsValid(indexPath: NSIndexPath) -> Bool {     return indexPath.section < numberOfSectionsInCollectionView(collectionView) && indexPath.row < collectionView.numberOfItemsInSection(indexPath.section) } 
like image 37
Andres Canella Avatar answered Sep 19 '22 14:09

Andres Canella