Search code examples
iosswiftswift3segueuistoryboardsegue

How can stop to jump next view controller? (swift)


I am using segue to send data from one viewController to destinationViewController. I set button and use push segue to connects to next view controller. In the first view, I set a boolean to check the images is or not empty. If there is any empty, it will pop up alert to remind users. If success, it will send the images to next view controller.

Although I can transmit the images and pop up the alert, it also jump to next view controller if there is any empty. Moreover, the alert is popped after jumping to next view controller, not in the first view controller

Now, here is the code

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

    if Jumpsuit.isHidden == false && self.Hair.image != nil && self.Jumpsuit.image != nil && self.Shoes.image != nil {

        let DestViewController : ChooseBGViewController = segue.destination as! ChooseBGViewController

        DestViewController.imgHair = Hair.image
        DestViewController.imgJumpsuit = Jumpsuit.image
        DestViewController.imgShoes = Shoes.image
        DestViewController.dressingtype = 1
    } else if Jumpsuit.isHidden == false && self.Hair.image == nil || self.Jumpsuit.image == nil || self.Shoes.image == nil {
        let alert = UIAlertView()
        alert.title = "No Image"
        alert.message = "Please check again"
        alert.addButton(withTitle: "OK")
        alert.show()

    }
}

How can I stop jumping to next view controller and pop up the alert in first view controller. Please help!


Solution

  • You can use shouldPerformSegue(withIdentifier:sender:) for that and return Bool value according your condtion.

    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
        if Jumpsuit.isHidden == false && self.Hair.image == nil || self.Jumpsuit.image == nil || self.Shoes.image == nil {
             //Show UIAlertController instead of UIAlertView it is deprecated
             return false
        }
        return true
    }