gpt4 book ai didi

swift - fatal error : Index out of range when click specific cells for segue

转载 作者:行者123 更新时间:2023-11-28 13:36:51 26 4
gpt4 key购买 nike

我正在尝试创建一个 segue,因此每次我单击一个 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)!]

}
}

当我单击某些行时,我的应用程序崩溃并显示 fatal error :索引超出范围

细节 View Controller


class DetailViewController: UIViewController {

@IBOutlet weak var compNameLbl: UILabel!

var ingredient : Ingredients?

override func viewDidLoad() {
super.viewDidLoad()

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


}
}

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

最佳答案

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]
}
}

DetailViewController中的ingredient类型改为String

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

关于swift - fatal error : Index out of range when click specific cells for segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56494429/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com