【问题标题】:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“尝试滚动到无效的索引路径
【发布时间】:2018-09-06 01:57:43
【问题描述】:

我的应用程序崩溃了,当我选择单元格 NO 时,我的 UICollectionView 中有 300 个单元格。 300 给我看这个崩溃:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“尝试滚动到无效的索引路径:{length = 2, path = 0 - 300}”

代码:

var EnabledID = Int()
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)
}

请帮我解决这个问题:)

【问题讨论】:

  • 崩溃前EnabledID的值是多少?如果该值为负数,您可以在第一行修正为EnabledID <= 0
  • 我编辑了我的代码@Matanya

标签: ios swift xcode crash uicollectionview


【解决方案1】:

检查数组计数

if EnabledID < arr.count
{
    let index = NSIndexPath(item: EnabledID, section: 0)
    self.myCollectionView.scrollToItem(at: index as IndexPath, at: .centeredHorizontally, animated: true)
}

【讨论】:

  • 你有 300 个单元格,最后是 299 个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 2018-04-05
  • 2013-04-27
  • 2021-09-17
  • 2012-07-12
  • 2021-02-03
  • 1970-01-01
相关资源
最近更新 更多