选择表格视图单元时无法一次触发segue

时间:2019-01-07 12:53:35

标签: ios swift

我正在制作一个待办事项列表应用程序,并且有两个View Controller,我必须将所选行的索引路径从CategoryViewController传递到ItemsViewController并触发Segue ... This Is my Category View Controller

但是,当我单击一个单元格时,它只是被选中,但不会触发segue Heres How 但是当我选择第一个单元格后选择另一个单元格时,就会触发segue ...这是我的代码

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "goToItems", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("sucess")

    let destinationVC = segue.destination as! ToDoListViewControlorer
    if let indexPath = tableView.indexPathForSelectedRow {
        destinationVC.selectedCategory = categoriesArray[indexPath.row]

    }

}

2 个答案:

答案 0 :(得分:0)

First, override didSelectRowAt method, because you want to handle moment when user select row, not deselect. Also as sender pass selected item

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    performSegue(withIdentifier: "goToItems", sender: categoriesArray[indexPath.row]) 
}

and then in prepare(for:sender:) just downcast sender

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationVC = segue.destination as? ToDoListViewControlorer {
        destinationVC.selectedCategory = sender as! Category
    }
}

p.s. name your controller Controller, not Controlorer

答案 1 :(得分:0)

Send your indexPath.row in sender argument of performSegue

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        performSegue(withIdentifier: "youridentifier", sender: indexPath.row)
}

get indexPath.row from the sender argument and pass to ToDoListViewControlorer

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("sucess")

    let destinationVC = segue.destination as! ToDoListViewControlorer
    if let indexPathRow = sender as? Int {
        destinationVC.selectedCategory = categoriesArray[indexPathRow]

    }

}