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.
indexPath(for:)Returns an index path that represents the row and section of a specified table-view cell.
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.
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 !=
You could check
- numberOfSections - numberOfItemsInSection:
of your UICollectionViewDataSource
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 } }
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With