获取所选行的索引以用于准备segue

时间:2018-09-16 08:26:30

标签: swift uitableview segue

我想根据选择的行将不同的数组从一个ViewController传递到另一个。 如何获取所选行的索引?
我已经尝试过了,但是不起作用:

let toDetailVCSegue = "ToDetailVCSegue"

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: toDetailVCSegue, sender: indexPath)
    }



     func prepare(for segue: UIStoryboardSegue, sender: IndexPath?)
    {
        if segue.identifier == toDetailVCSegue
        {
        let destination = segue.destination as! DetailViewController
            if let indexPath = tableView.indexPathForSelectedRow{
                if indexPath.row == 0 {
                    destination.itemArray = namesArray
                    print("test")
                }
                if indexPath.row == 1 {
                    destination.itemArray = scoresArray
                }
                if indexPath.row == 2 {
                    destination.itemArray = timesArray
                }
                if indexPath.row == 3 {
                    destination.itemArray = completedArray
                }

            }
        }
    } 

2 个答案:

答案 0 :(得分:5)

不得更改prepare(for的签名,否则将不会被调用。 sender参数必须为Any?

sender参数设置为IndexPath,我建议使用switch语句

func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.identifier == toDetailVCSegue {
        let destination = segue.destination as! DetailViewController
        let indexPath = sender as! IndexPath
        switch indexPath.row {
          case 0: destination.itemArray = namesArray
          case 1: destination.itemArray = scoresArray
          case 2: destination.itemArray = timesArray             
          case 3: destination.itemArray = completedArray
          default: break
        }
    }
} 

答案 1 :(得分:0)

尝试一下

let toDetailVCSegue = "ToDetailVCSegue"

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: toDetailVCSegue, sender: indexPath)
}

func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if  
        let destination = segue.destination as? DetailViewController, 
        let indexPath = sender as? IndexPath {

            switch indexPath.row {
            case 0: destination.itemArray = namesArray
            case 1: destination.itemArray = scoresArray
            case 2: destination.itemArray = timesArray             
            case 3: destination.itemArray = completedArray
            default: break

        }
    }

}