Swift 致命错误:单击segue的特定单元格时索引超出范围
我正在尝试创建一个segue,因此每次单击tableView行时,都会显示另一个具有特定行信息的ViewController 我从Firestore填充数据 基本上每个文档都包含一个数组,然后我按行填充数组的字符串Swift 致命错误:单击segue的特定单元格时索引超出范围,swift,uitableview,Swift,Uitableview,我正在尝试创建一个segue,因此每次单击tableView行时,都会显示另一个具有特定行信息的ViewController 我从Firestore填充数据 基本上每个文档都包含一个数组,然后我按行填充数组的字符串 var ingredientsArray = [Ingredients]() func numberOfSections(in tableView: UITableView) -> Int { return ingredientsArray.count
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)!]
}
}
当我单击某些行时,我的应用程序崩溃并出现致命错误:索引超出范围
详细视图控制器
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
class DetailViewController: UIViewController {
@IBOutlet weak var compNameLbl: UILabel!
var ingredient : String?
override func viewDidLoad() {
super.viewDidLoad()
compNameLbl.text = ingredient
}
}
什么意思?我怎么能看到呢?使用
destination.component=ingredientsArray[(tableView.indexPathForSelectedRow?.section)!]
非常感谢。我只是把行改成了节。最后一件事是,当我单击该行时,我想在compNameLbl
中显示该行的名称,但我得到了整个数组。工作非常顺利。谢谢!