(Thread1:fatal error: index out of range error) showing this error in myCell.imageView?.image = myImages[indexPath.row]

时间:2018-07-25 05:25:18

标签: ios swift uitableview

import UIKit

class ViewController: UIViewController, UITableViewDataSource {
    let myFruit: [[String]] = [["apple", "orange", "water mellon", "pineapple", "lemon", "Lime", "another fruit" ], ["green", "orange", "green/red", "yellow", "green"]]

    let myTitles: [String] = ["Fruits", "Color of Fruits"]

    let myImages: [UIImage] = [#imageLiteral(resourceName: "dd"),#imageLiteral(resourceName: "logo"),#imageLiteral(resourceName: "nn"),#imageLiteral(resourceName: "r"),#imageLiteral(resourceName: "xx"),#imageLiteral(resourceName: "zz")]

    func numberOfSections(in tableView: UITableView) -> Int {
        return myFruit.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return myFruit[section].count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return myTitles[section]
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let myCell = tableView.dequeueReusableCell(withIdentifier: "myCoolCell", for: indexPath)
        myCell.textLabel?.text = myFruit[indexPath.section][indexPath.row]
        myCell.imageView?.image = myImages[indexPath.row]
        return myCell
    }
}

(Thread1:fatal error: index out of range error) showing this error in myCell.imageView?.image = myImages[indexPath.row]

1 个答案:

答案 0 :(得分:1)

finally数组中,数组内部有7个索引为0的项。而myFruit中有6个项。您返回的myImages为7(numberOfRowsInSection,因此您的应用将在myFruit[section].count时崩溃,因为indexPath.row = 6数组中的项直到myImages为止。

您应该确保indexPath.row = 5数组的图像数量始终与myImages相同。

OR

您可以在从numberOfRowsInSection数组访问图像之前添加条件,

myImages