Swift超出范围…与tableView

我遇到了超出range错误…

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

如果我把cell.nameLabel.text = nameArray[(indexPath as NSIndexPath).row] 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 } 

你需要检查你的数组。 从我在这里可以看到, numOfDays有更less的元素,然后nameArray 。 此外,当你在那里检查creditArray以及:)

此外,转换到NSIndexPath是没有必要的。

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

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

 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的转换(单元格将总是再次绘制,因为它是新的)。

Interesting Posts