Search code examples
iosxcodeswiftstoryboardsegue

iOS Xcode (swift) - how to execute code after unwind segue


I perform a segue from scene 1 to scene 2. I then return from scene 2 to scene 1. How do I not only pass data from scene 2 to scene 1 but detect in scene 1 that I've returned from scene 2 and execute code in scene 1?

In Android I do this with startActivity and onActivityResult.


Solution

  • Introducing Bool state like the other answer's suggesting is very bad and must be avoided if possible as it greatly increases the complexity of your app.

    Amongst many other patterns, easiest one to solve this kind of problem is by passing delegate object to Controller2.

    protocol Controller2Delegate {
      func controller2DidReturn()
    }
    
    class Controller1: Controller2Delegate {
      func controller2DidReturn() {
        // your code.
      }
    
      func prepareForSegue(...) {
        // get controller2 instance
    
        controller2.delegate = self
      }
    }
    
    class Controller2 {
      var delegate: Controller2Delegate!
    
      func done() {
        // dismiss viewcontroller
    
        delegate.controller2DidReturn()
      }
    }
    

    States are evil and is the single biggest source of software bugs.