How can I check to see whether an indexPath is valid or not?
I want to scroll to an index path, but I sometimes get an error if my collection view's subviews aren't finished loading.
How can I check to see whether an indexPath is valid or not?
I want to scroll to an index path, but I sometimes get an error if my collection view's subviews aren't finished loading.
You could check
of your
UICollectionViewDataSource
to see if your indexPath is a valid one.A more concise solution?
or more compact, but less readable...
Here's a Swift 4 snippet I wrote and have been using for a while. It lets you either scroll to an IndexPath only if it's available, or - throw an error if the IndexPath is not available, to let you control what you want to do in this situation.
Check out the code here:
https://gist.github.com/freak4pc/0f244f41a5379f001571809197e72b90
It lets you do either:
Or
The latter would throw something like:
expression unexpectedly raised an error: IndexPath [0, 2000] is not available. The last available IndexPath is [0, 36]
Using swift extension:
If you are trying to set the state of a cell in the collection view without knowing whether the index path is valid or not, you could try saving the indices for cells with a special state, and set the state of the cells while loading them.
@ABakerSmith's answer is close, but not quite right.
The answer depends on your model.
If you have a multi-section collection view (or table view for that matter - same issue) then it's pretty common to use an array of arrays to save your data.
The outer array contains your sections, and each inner array contains the rows for that section.
So you might have something like this:
In that case, when presented with an indexPath, you'd need to interrogate your model object (myTableViewData, in the above example)
The code might look like this:
EDIT:
@ABakerSmith has an interesting twist: Asking the data source. That way you can write a solution that works regardless of the data model. His code is close, but still not quite right. It should really be this: