ios - '尝试滚动到无效的索引路径 : {length = 2, path = 0 - 4}

标签 ios swift uicollectionview

我有一个水平 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/

相关文章:

ios - CGImageDestinationCreateWithURL 的问题

ios - 委托(delegate)有问题,我的委托(delegate)总是零,tvOS,swift 2.0

swift - 如何制作水平滚动的 2 行多列 UICollectionView

swift - 从 Silver 命令行在 Windows 上编译 Swift?

swift - 在 Swift 3 中使用 NSHashTable 实现观察者模式

ios - UIView animateWithDuration 不适用于 UISlider

objective-c - 在 MPMoviePlayerController 中禁用用户交互

swift - UICollectionView insertItems(位于:) not completing before other code

ios - UITableViewCellaccessoryView在iOS 13上有灰色背景颜色

ios - 收据对齐在 swift 中无法正常工作