我有一个带有以下willSelectRowAt
代码的表格视图:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
for n in 0...carsArray.count - 1 {
if indexPath.row == n {
print(carsArray[n].name)
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToEditCar" {
let name = carsArray[n].name
print(name)
let indexCar = n
let destinationVC = segue.destination as! EditCarViewController
destinationVC.name = name
destinationVC.indexCar = indexCar
}
}
performSegue(withIdentifier: "goToEditCar", sender: self)
}
}
}
prepare
函数不会以某种方式传递所需的数据,print(name)
也不会传递-有人可以告诉我这段代码的问题吗?
答案 0 :(得分:4)
您的代码根本无法工作。您使用了错误的API,prepare(for
永远不会在另一个方法中被调用,实际上您不需要循环。
willSelectRowAt
用于控制是否允许选择单元格。返回indexPath
(如果允许的话),否则返回nil
这不是您想要的。使用didSelect
并在调用sender
performSegue
传递
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToEditCar", sender: indexPath)
}
在prepare(for
中,从sender
参数获取索引路径
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToEditCar" {
let indexPath = sender as! IndexPath
let name = carsArray[indexPath.row].name
print(name)
let destinationVC = segue.destination as! EditCarViewController
destinationVC.name = name
destinationVC.indexCar = indexPath.row
}
}
答案 1 :(得分:2)
这里不需要for循环,因为n
最终将等于indexPath.row
,也应该使用didSelectRowAt
func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToEditCar", sender:indexPath.row)
}
func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToEditCar" {
let index = sender as! Int
let destinationVC = segue.destination as! EditCarViewController
destinationVC.name = carsArray[index].name
destinationVC.indexCar = index
}
}