我有一个水平的收藏夹视图,用作4个屏幕/步骤的寻呼机。我禁用了水平滚动作为仅通过浮动按钮执行下一步操作的方式:
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)
}
我第二次点击按钮,应用崩溃。
] *由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:“试图滚动到无效 索引路径:{length = 2,路径= 0-4}' * 第一个调用堆栈:(0 CoreFoundation 0x00000001088dd6fb __exceptionPreprocess + 331 1 libobjc.A.dylib
0x0000000107e81ac5 objc_exception_throw + 48 2 CoreFoundation
0x00000001088dd555 + [NSException提高:格式:] + 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
答案 0 :(得分:1)
4个屏幕/步骤由索引0-3表示。该错误明确指出了超出范围的错误。
您必须检查nextItem
是否达到结束索引
let nextItem = self.selectedIndexPath.item + 1
if nextItem < 4 {
self.scrollToStep(index: IndexPath(item: nextItem, section: 0))
}
答案 1 :(得分:1)
var staticIndex = 0
在按钮单击操作中
if staticIndex < 3 {
var indexPath = IndexPath.init(row: staticIndex+1, section: 0)
collectionView.scrollToItem(at: indexPath, at: .right, animated: true)
staticIndex += 1
}