【问题标题】:Swift out of range.... with tableView[indexPath]Swift 超出范围.... 使用 tableView[indexPath]
【发布时间】:2017-07-14 07:43:53
【问题描述】:

我遇到了range 错误...

错误发生在cell.creditLabel.text = numOfDays[(indexPath as NSIndexPath).row] + "days"

如果我把tableView.reloadData()放在cell.nameLabel.text = nameArray[(indexPath as NSIndexPath).row]之后

然后模拟器中什么都没有显示...

我该如何解决这个问题..?

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return self.nameArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell : MoneyTableViewCell = tableView.dequeueReusableCell(withIdentifier: "MoneyTableViewCell", for: indexPath) as! MoneyTableViewCell


    cell.nameLabel.text = nameArray[(indexPath as NSIndexPath).row]

    cell.creditLabel.text = numOfDays[(indexPath as NSIndexPath).row] + "days"
    cell.levelLabel.text = creditArray[(indexPath as NSIndexPath).row]

    cell.layoutIfNeeded()

    return cell
}

【问题讨论】:

  • 如果我将 tableView.reloadData() 放在 cell.nameLabel.text = nameArray[(indexPath as NSIndexPath).row] 之后,那么模拟器中什么也不会出现......你不应该把 table-view重新加载它。然后它将在无限循环中运行。您不应该强制类型转换为 NSIndexPathm 索引路径行将起作用
  • “我怎样才能解决这个问题..?”——这就是所谓的调试。数组有多少个元素?您要访问哪个元素?为什么数组的元素比你想象的要少? ...想想!
  • @MartinR 你是对的。我是程序员界的新手,所以我会多练习。感谢您的建议....

标签: ios swift uitableview indexpath


【解决方案1】:

您需要检查您的阵列。从我在这里可以看到,numOfDays 的元素少于nameArray。另外,当你在那里时,请检查creditArray :)

另外,也不需要强制转换为 NSIndexPath

【讨论】:

  • 谢谢。我检查了调试区域,发现我在 nameArray 中有 14 个元素。名称数组和 numOfDays 中应该有 7 个原子,但我仍然不知道为什么有 14 个。
  • 无论如何我只是将 nameArray.count 更改为 creditArray.count 然后现在可以工作了。再次感谢你:)
  • 可能你已经添加到 nameArray 两次。仔细检查数据准备函数。
  • 我还在想办法,但很难找到。我想知道如果我使用 tableView.reloadData(),是否意味着 tableView() 与 cellforRow 再次调用?
  • 是的,reloadData 会调用 cellforRow
【解决方案2】:

“numOfDays”数组中的元素数小于“nameArray”数组中的元素数

【讨论】:

  • 我认为发布已经发布的答案不是一个好主意!
【解决方案3】:

检查数组中的项目数量是否正确:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return self.nameArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell : MoneyTableViewCell = tableView.dequeueReusableCell(withIdentifier: "MoneyTableViewCell", for: indexPath) as! MoneyTableViewCell


    cell.nameLabel.text = nameArray[indexPath.row]

    if numOfDays.count < indexPath.row {
        cell.creditLabel.text = numOfDays[indexPath.row] + "days"
    }

    if creditArray.count < indexPath.row {
        cell.levelLabel.text = creditArray[indexPath.row]
    }

    return cell
}

此外,我还删除了 indexPath 和 layoutIfNeeded 的不必要转换(单元格总是会再次绘制,因为它是新的)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2018-05-07
    相关资源
    最近更新 更多