Reputation: 5407
I have a horizontal collection view working as a pager of 4 screens/steps. I disabled the horizontal scrolling as a way to perform next action only from a floating button:
let nextItem = self.selectedIndexPath.item + 1
self.scrollToStep(index: IndexPath(item: nextItem, section: 0))
func scrollToStep(index: IndexPath){
selectedIndexPath = index
collectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: true)
}
The second time I tap the button the app crashes.
] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: {length = 2, path = 0 - 4}' * First throw call stack: ( 0 CoreFoundation 0x00000001088dd6fb __exceptionPreprocess + 331 1 libobjc.A.dylib
0x0000000107e81ac5 objc_exception_throw + 48 2 CoreFoundation
0x00000001088dd555 +[NSException raise:format:] + 197 3 UIKitCore
0x000000010b79ef93 -[UICollectionView _contentOffsetForScrollingToItemAtIndexPath:atScrollPosition:] + 212 4 UIKitCore 0x000000010b79f86b -[UICollectionView _scrollToItemAtIndexPath:atScrollPosition:animated:] + 70 5 0x0000000105238770 $s14 18ViewControllerC12scrollToStep5indexy10Foundation9IndexPathV_tF + 480 6 0x00000001052358b5 $s1 ar 010collectionF0_13cellForItemAtSo012UICollectionF4CellCSo0mF0C_10Foundation9IndexPathVtFySbcfU_ + 1701
Upvotes: 1
Views: 6966
Reputation: 741
var staticIndex = 0
in button click action
if staticIndex < 3 {
var indexPath = IndexPath.init(row: staticIndex+1, section: 0)
collectionView.scrollToItem(at: indexPath, at: .right, animated: true)
staticIndex += 1
}
Upvotes: 2
Reputation: 285069
4 screens/steps are represented by the indices 0 - 3. The error clearly states an out-of-range error.
You have to check if nextItem
reaches the end index
let nextItem = self.selectedIndexPath.item + 1
if nextItem < 4 {
self.scrollToStep(index: IndexPath(item: nextItem, section: 0))
}
Upvotes: 3