我想根据选择的行将不同的数组从一个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
}
}
}
}
答案 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
}
}
}