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]
答案 0 :(得分:1)
在finally
数组中,数组内部有7个索引为0的项。而myFruit
中有6个项。您返回的myImages
为7(numberOfRowsInSection
,因此您的应用将在myFruit[section].count
时崩溃,因为indexPath.row = 6
数组中的项直到myImages
为止。
您应该确保indexPath.row = 5
数组的图像数量始终与myImages
相同。
OR
您可以在从numberOfRowsInSection
数组访问图像之前添加条件,
myImages