Prateek
Prateek

Reputation: 1754

Choose segue based on condition

I want to choose a segue for my UITableVieController cells based on whether the data for a row matches. I have 2 segues currently (only one from the cell as that's the maximum I could do) but I can't seem to get it to work.

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
}

Essentially, the cell's 'free' value is 1 then it needs to go to one view controller, otherwise it will go to another.

Upvotes: 0

Views: 54

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100523

Don't do performSegue inside shouldPerformSegue you need to check the value before you do the perform and act accordingly as this will cause a recursive calls as performSegue will call shouldPerformSegue again and infinitely

You need to place this inside didSelectRowAt

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

with hooking the source of the segue to the vc itself not to the cell

Upvotes: 1

Related Questions