根据条件选择segue

Choose segue based on condition

我想根据行的数据是否匹配为我的 UITableVieController 单元格选择一个 segue。我目前有 2 个 segues(只有一个来自单元格,因为这是我能做的最大值)但我似乎无法让它工作。

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

    let indexPath = self.tableView.indexPathForSelectedRow
    let free = allAlbums[indexPath!.row].free

    if free == "1"
    {

        if segue.destination is CaseViewController
        {
            let vc = segue.destination as? CaseViewController


            vc?.title = allAlbums[indexPath!.row].title
        }
    }
    else {
    }
}

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {

    if identifier == "caseDetail" {
        let indexPath = self.tableView.indexPathForSelectedRow
        let free = allAlbums[indexPath!.row].free
        if free == "1"
        {
            self.performSegue(withIdentifier: "caseDetail", sender: self)
        }
        else {
            self.performSegue(withIdentifier: "paidCase", sender: self)
        }
    }

    return true
}

本质上,单元格的'free'值是1那么它需要转到一个视图控制器,否则它会转到另一个。

不要在 shouldPerformSegue 中执行 performSegue 您需要在执行之前检查该值并采取相应措施,因为这将导致递归调用,因为 performSegue 将调用 shouldPerformSegue 一次又一次无限

你需要把它放在里面 didSelectRowAt

let free = allAlbums[indexPath.row].free
if free == "1"  {
  self.performSegue(withIdentifier: "caseDetail", sender: self)
}
else {
   self.performSegue(withIdentifier: "paidCase", sender: self)
}

将 segue 的源挂钩到 vc 本身而不是单元格