Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 551
Questioner Avatar asked Nov 26 '15 09:11

Questioner


People also ask

How do you use unwind segue in Swift?

Connect a triggering object to the exit control In your storyboard, create an unwind segue by right-clicking a triggering object and dragging to the Exit control at the top of your view controller's scene.

How do you segue back in Swift?

Set up the project Create three new view controllers in the Storyboard (I'm going to call them View Controller A, B, and C.) Embed them in a navigation controller (Editor → Embed In → Navigation Controller) Create a show segue from View Controller A to B and from B to C. Give each a unique identifier.


1 Answers

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.

like image 106
Daniel Shin Avatar answered Sep 22 '22 06:09

Daniel Shin