John John - 1 year ago 91
iOS Question

How to add If statement before unwinding segue?

I have 2 views: FirstView and SecondView.

On SecondView, there are a textfield and a Submit button.
If user click Submit button, check if textfield is empty or not before going back to FirstView.

On StoryBoard of SecondView, I create a Unwind Segue by hold Ctrl and click on Submit button, then drag to Exit and choose


On FirstViewController:

@IBAction func tapToBackToFirstView (segue: UIStoryboardSegue) {


On SecondViewController:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "backToFirstViewFromSecondView" {
let destinationController = segue.destination as! FirstViewController
destinationController.resultLabel.text = secondViewTextField.Text

From my code, If I click on Submit button, it always go to FirstView.
How can I add a IF statement to check if the textfield is empty or not? If it is empty, show an alert and DO NOT go to FirstView.

If it is not empty, go to FirstView.


Answer Source

On your FirstView Controller you have unwindseguemethod tapToBackToFirstView which is connected from button action right?. Now remove that and instead of connecting unwind segue through IBAction, just drag from SecondViewController to it's own exit so that you will get one manual segue created. Give a segue identifier to this.

Now connection IBAction normally just like any button. call performSegueWithIdentifier in this based on condition.

@IBAction func tapToBackToFirstView(sender: AnyObject) {
    if //Add your condition here
        {performSegueWithIdentifier("segue identifier", sender: self)}
    else {
        //Do this
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download