47

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.

Zouhair Sassi
  • 1,403
  • 1
  • 13
  • 30
webmagnets
  • 2,266
  • 3
  • 33
  • 60

9 Answers9

59

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
    }

}
iwasrobbed
  • 46,496
  • 21
  • 150
  • 195
muffe
  • 2,285
  • 1
  • 19
  • 23
  • This is giving me `EXC_BAD_ACCESS (code=1, address=0xfffffffffffffff8) numberOfRows` :/ (I am using for table view, but I think the concept is same?) – Parth Jan 15 '21 at 06:29
27

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)
}
Andres Canella
  • 3,706
  • 1
  • 35
  • 47
12

@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:

struct TableViewData
{
  //Dummy structure, replaced with whatever you might use instead
  var heading: String
  var subHead: String
  var value: Int
}

typealias RowArray: [TableViewData]

typeAlias SectionArray: [RowArray]


var myTableViewData: SectionArray

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:

func indexPathIsValid(theIndexPath: NSIndexPath) -> Bool
{
  let section = theIndexPath.section!
  let row = theIndexPath.row!
  if section > myTableViewData.count-1
  {
    return false
  }
  let aRow = myTableViewData[section]
  return aRow.count < row
}

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:

func indexPathIsValid(indexPath: NSIndexPath) -> Bool 
{
  let section = indexPath.section!
  let row = indexPath.row!

  let lastSectionIndex = 
    numberOfSectionsInCollectionView(collectionView) - 1

  //Make sure the specified section exists
  if section > lastSectionIndex
  {
    return false
  }
  let rowCount = self.collectionView(
    collectionView, numberOfItemsInSection: indexPath.section) - 1

  return row <= rowCount
}
tommy chheng
  • 9,108
  • 9
  • 55
  • 72
Duncan C
  • 128,072
  • 22
  • 173
  • 272
7

Using swift extension:

extension UICollectionView {

  func validate(indexPath: IndexPath) -> Bool {
    if indexPath.section >= numberOfSections {
      return false
    }

    if indexPath.row >= numberOfItems(inSection: indexPath.section) {
      return false
    }

    return true
  }

}

// Usage
let indexPath = IndexPath(item: 10, section: 0)

if sampleCollectionView.validate(indexPath: indexPath) {
  sampleCollectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.centeredHorizontally, animated: true)
}
Ashok
  • 5,585
  • 5
  • 52
  • 80
  • 0 is a valid row and section. Following your logic indexPath will be considered invalid since you assigned a section of 0, while the inverse is true since you're validating an index against a count. – Alex Blair Dec 13 '18 at 01:34
6

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:

myCollectionView.scrollToItemIfAvailable(at: indexPath, at: .top, animated: true)

Or

myCollectionView.scrollToItemOrThrow(at: indexPath, at: .top, animated: true)

The latter would throw something like:

expression unexpectedly raised an error: IndexPath [0, 2000] is not available. The last available IndexPath is [0, 36]

Shai Mishali
  • 9,224
  • 4
  • 56
  • 83
2

Objective C version:

- (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
{
    return indexPath.section < [self.collectionView numberOfSections] && indexPath.row < [self.collectionView numberOfItemsInSection:indexPath.section];
}
Denis Kutlubaev
  • 15,320
  • 6
  • 84
  • 70
0

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.

carrotzoe
  • 127
  • 1
  • 1
  • 8
0

You should check the validation of the index paths that will be appended with the data source(future state) and the deletion of index paths with the current existing ones(present state).

extension UITableView {

func isValid(indexPath: IndexPath, inDataSource: Bool = false) -> Bool {
    guard
        let numberOfSections = inDataSource
            ? dataSource?.numberOfSections?(in: self)
            : numberOfSections,
        let numberOfRows = inDataSource
            ? dataSource?.tableView(self, numberOfRowsInSection: indexPath.section)
            : numberOfRows(inSection: indexPath.section)
    else {
        preconditionFailure("There must be a datasource to validate an index path")
    }
    return indexPath.section < numberOfSections && indexPath.row < numberOfRows
}

usage:

// insert    
tableView.insertRows(at: indexPaths.filter({ tableView.isValid(indexPath: $0, inDataSource: true) }), with: .top)

// remove
tableView.deleteRows(at: indexPaths.filter({ tableView.isValid(indexPath: $0) }), with: .top)

output:

true or false
Lloyd Keijzer
  • 1,229
  • 1
  • 12
  • 22
-3

Perhaps this is what you're looking for?

- (UICollectionViewCell *)cellForItemAtIndexPath:(NSIndexPath *)indexPath

Return Value: The cell object at the corresponding index path or nil if the cell is not visible or indexPath is out of range.

pkamb
  • 33,281
  • 23
  • 160
  • 191
Thorory
  • 1
  • 2
  • 3
    That won't work because it will return nil if the indexPath exists in your data model but is not currently on-screen. – Duncan C Apr 08 '15 at 14:25
  • I thought that was the problem, namely that the item does exist (in the model), but hasn't finished displaying. – Thorory Apr 08 '15 at 15:23
  • Hmm. You might be right. It isn't totally clear from the OP's question. Another possibility is simply to make an explicit call to `reloadData` immediately after changing the model. – Duncan C Apr 08 '15 at 15:31