Search code examples
swiftuitableviewuicollectionviewcellnsindexpath

Swift - NSInvalidArgumentException and NSIndexPath


I have TableView with 14 cells and in each cell has a CollectionView with 25 cells, when transfer from cell number 24 to cell 25 show me crash!

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: {length = 2, path = 0 - 25}'

Code:

var EnabledID = Int()

override func viewWillAppear(_ animated: Bool) {

    EnabledID = UserDefaults.standard.integer(forKey: "EnabledID")

    if EnabledID == 0 {

        EnabledID = 1
        UserDefaults.standard.set(1, forKey: "EnabledID")

    } else {

        let index = NSIndexPath(item: EnabledID, section: 0)
        self.myCollectionView.scrollToItem(at: index as IndexPath, at: .centeredHorizontally, animated: true)

    }

}

Above code I want to after complete any cell the scroll automatically go to next cell in CollectionView.

What is the solve ???


Solution

  • Please add a condition to check that indexPath is existed or not(because index is started from 0 so your indexes like 0-24 and index path 25 will not exist so please add a check before reload):

    override func viewWillAppear(_ animated: Bool) {
    
        EnabledID = UserDefaults.standard.integer(forKey: "EnabledID")
    
        if EnabledID == 0 {
    
            EnabledID = 1
            UserDefaults.standard.set(1, forKey: "EnabledID")
    
        } else {
    
           let totelCells = myCollectionView.numberOfItems(inSection: 0)
           if totelCells > EnabledID {
            let index = NSIndexPath(item: EnabledID, section: 0)
            self.myCollectionView.scrollToItem(at: index as IndexPath, at: .centeredHorizontally, animated: true)
    
          }
        }
    
    }