Swift out of range… with tableView[indexPath]

感情迁移 提交于 2019-12-12 05:30:02

问题


I'm getting trouble with out of range error...

The error occurs in cell.creditLabel.text = numOfDays[(indexPath as NSIndexPath).row] + "days".

And if I put tableView.reloadData() after cell.nameLabel.text = nameArray[(indexPath as NSIndexPath).row]

then nothing shows up in the simulator...

How can I fix this problem..?

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
}

回答1:


You need to check your arrays. From what I can see here, numOfDays have less elements then nameArray. Also, while you are there check creditArray as well :)

Also, cast to NSIndexPath is not necessary.




回答2:


Number of elements in "numOfDays" array are less than number of elements in "nameArray" array




回答3:


Check that the arrays have the correct amount of items:

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
}

Also, I have removed the unnecessary casting of indexPath and the layoutIfNeeded (the cell will always draw again, since it is new).



来源:https://stackoverflow.com/questions/45097448/swift-out-of-range-with-tableviewindexpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!