Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios (Thread1:致命错误:索引超出范围错误)在myCell.imageView?.image=myImages[indexath.row]中显示此错误_Ios_Swift_Uitableview - Fatal编程技术网

Ios (Thread1:致命错误:索引超出范围错误)在myCell.imageView?.image=myImages[indexath.row]中显示此错误

Ios (Thread1:致命错误:索引超出范围错误)在myCell.imageView?.image=myImages[indexath.row]中显示此错误,ios,swift,uitableview,Ios,Swift,Uitableview,(Thread1:致命错误:索引超出范围错误)在myCell.imageView?.image=myImages[indexath.row]中显示此错误 在myFruit数组中,数组中索引0处有7项。而myImages中有6个项目。您将numberofrowsinssection返回为7(myFruit[section].count),因此当indexPath.row=6时,您的应用程序将崩溃,因为myImages数组中的项一直到indexPath.row=5 或者,您应该确保您的myImage

(Thread1:致命错误:索引超出范围错误)在myCell.imageView?.image=myImages[indexath.row]中显示此错误


myFruit
数组中,数组中索引0处有7项。而
myImages
中有6个项目。您将
numberofrowsinssection
返回为7(
myFruit[section].count
),因此当
indexPath.row=6
时,您的应用程序将崩溃,因为
myImages
数组中的项一直到
indexPath.row=5

或者,您应该确保您的
myImages
数组的图像数始终与
numberofrowsin节的图像数相同

您可以在从
myImages
数组访问图像之前添加条件,如下所示:

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
    }
}
如果indexath.row
问题比这严重得多。代码在多个节中获取多行的单元格文本,但不管节是什么,图像都是基于行的。这毫无意义。文本和图像之间需要1:1的匹配。应该只有一个数据数组,而不是两个单独的数据数组。
if indexPath.row < myImages.count {
    myCell.imageView?.image = myImages[indexPath.row]
}