准备在for循环内进行锁定

时间:2019-05-20 17:37:45

标签: ios swift

我有一个带有以下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)也不会传递-有人可以告诉我这段代码的问题吗?

2 个答案:

答案 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
        }
}