Search code examples
swiftuiviewcontrolleribaction

Swift - Run IBAction before unwinding from view controller


So I have a "Save" button on a view controller, we'll call VC2. When clicked, it unwinds back the original view controller, we'll call VC1.

However, I want to run some logic on the data from VC2 before I pass it back to VC1. I tried mapping an IBAction from the Save button that exits VC2 and runs the unwind code on VC1. But I noticed it doesn't run the IBAction mapped to the button. I'm guess this is because it's linked to exit.

So my question is: if I have a button that exits my view controller, can I also have it linked to an IBAction so that I can run some logic on the view controller being exited (VC2) before it exists?


Solution

  • If your button is linked to a segue on the storyboard, its IBActions does not seem to run. I don't know if this is documented anywhere, but that seems to be the behaviour.

    Instead of linking the button to the "Exit" of VC1, link your VC2 to the "Exit", then give that unwind segue an identifier, let's say unwindToVC1.

    Now you can add your IBAction to the button, and write:

    @IBAction func buttonPress() {
        // process your data or whatever
    
        // perform the unwind segue
        performSegue(withIdentifier: "unwindToVC1", sender: yourData)
    }