致命错误:单击特定单元格进行搜索时,索引超出范围

时间:2019-06-07 12:33:20

标签: swift uitableview

我试图创建一个序列,因此每次我单击tableView行时,都显示另一个ViewController以及该行的信息。

我从Firestore填充数据。

基本上每个文档都包含一个数组,然后我在行中填充该数组的字符串

var ingredientsArray = [Ingredients]()

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

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

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        performSegue(withIdentifier: "SearchDetails", sender: self)
    }


     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "IngredientCell", for: indexPath) as! IngredientTableViewCell

        cell.populate(ingredient: ingredientsArray[indexPath.section])
        let item1 = ingredientsArray[indexPath.section].compName[indexPath.row]
        cell.ingredientNameLabel.text = ("\(item1)")

        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? DetailViewController{

//HERE IS THE ERROR.
            destination.ingredient = ingredientsArray[(tableView.indexPathForSelectedRow?.row)!]

        }
    }

当我单击某些行时,我的应用程序崩溃并且出现致命错误:索引超出范围

DetailViewController


class DetailViewController: UIViewController {

    @IBOutlet weak var compNameLbl: UILabel!

    var ingredient : Ingredients?

    override func viewDidLoad() {
        super.viewDidLoad()

        compNameLbl.text = "\((ingredient?.compName)!)"


    }
}

另外,当我尝试在标签中显示名称时,整个数组就会出现。

1 个答案:

答案 0 :(得分:1)

compName数组中获取字符串值并传递该值

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? DetailViewController, let indexPath = tableView.indexPathForSelectedRow {
        destination.ingredient = ingredientsArray[indexPath.section].compName[indexPath.row]
    }
}

ingredient中将String类型更改为DetailViewController

class DetailViewController: UIViewController {    
    @IBOutlet weak var compNameLbl: UILabel!
    var ingredient : String?
    override func viewDidLoad() {
        super.viewDidLoad()
        compNameLbl.text = ingredient
    }
}