Search code examples
iosswiftxcodeuinavigationcontrolleruistoryboardsegue

How to prevent navigation to UIViewController checking a condition?


I've a button that show a view controller (ViewControllerIncluirItem). But, I need check a condition before navigate, I try check this inside func override func prepare(for segue: UIStoryboardSegue, sender: Any?). But, the navigation ocurrs for any way. I did tried this:

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

        if segue.identifier == "SegueToVcIncluirItem" {

            if pricelist != nil {
                print("pricelist ok")              
            } else {
                print("selecione pricelist")
                return // Here I want prevent.
            }

            let nav = segue.destination as! UINavigationController
            let childVc = nav.topViewController as! ViewControllerIncluirItem
            childVc.strTeste = "testado com sucesso"
        }
    }

Solution

  • You can check your condition in the method shouldPerformSegue(withIdentifier:sender:)

    Your code should look like this:

        func shouldPerformSegue(withIdentifier identifier: String,
                                sender: Any?) -> Bool{
    
            if identifier == "SegueToVcIncluirItem" {
               return pricelist != nil
            }
    
            return true
        }