我有一个水平 Collection View ,用作 4 个屏幕/步骤的寻呼机。我禁用了水平滚 Action 为仅从 float 按钮执行下一个操作的一种方式:
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)
}
我第二次点击按钮时应用程序崩溃。
] * 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
最佳答案
4 个屏幕/步骤由索引 0 - 3 表示。错误清楚地表明了超出范围的错误。
您必须检查 nextItem
到达结束索引
let nextItem = self.selectedIndexPath.item + 1
if nextItem < 4 {
self.scrollToStep(index: IndexPath(item: nextItem, section: 0))
}
关于ios - '尝试滚动到无效的索引路径 : {length = 2, path = 0 - 4},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55473288/