Swift out of range.... with tableView[indexPath]



我遇到了错误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
}

您需要检查数组。从我在这里看到的,numOfDays的元素比nameArray少.另外,当您在那里时,请检查creditArray以及:)

此外,不需要强制转换为NSIndexPath

"numOfDays" 数组中的元素数小于 "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 和 layoutIfNeed 的不必要的强制转换(单元格将始终再次绘制,因为它是新的(。

最新更新