问题
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