0
votes

I have a button on 2nd viewController, after pressing that button, I would like to dismiss the 2nd viewController and go back to the 1st view controller and immediately call a function that coded inside 1st ViewController swift file.

May I know how can I do that? By segue?

2
You can set 1st viewcontroller is delegate property of 2nd view controller. When press button, call delegate function to 1st viewcontroller - larva
When the second view controller is presented pass a closure as a callback and call the closure in the IBAction. - vadian

2 Answers

2
votes

There are many way to do this one of the best way is using protocol and delegate.

You can create one protocol and extend that protocol in your ViewController1. Now create the delegate of protocol in ViewController2 and pass reference of that delegate in the ViewController1's prepareForSegue method.

First create one protocol like this

protocol PassdataDelegate {

    func passData()
}

Now extend this protocol in ViewController1 like this and pass the reference of delegate in prepareForSegue method

class ViewController1 : UIViewController, PassdataDelegate {


    func passData() {
        //Here call your function 
        self.callMyFunction()
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "SegueIdentifier") {
             let destVC = segue.destinationViewController as! ViewController2
             destVC.delegate = self 
        }
    }
}

Now create the delegate object of protocolin ViewController2 like this

class ViewController2 : UIViewController {

    var delegate: PassdataDelegate?

    //Now call the method of this delegate in Button action
    @IBAction func buttonClick(sender: UIButton) {
         self.delegate.passData()
         //Now dismiss the controller
    }
}

Note: - Here i am passing stringbut you can pass any type of object that you have declare in your delegate method.

1
votes

You can refer unwind segue.

class ViewController1 {
  @IBAction func doSomeStuffAfterReload(segue: UIStoryboardSegue) {
    // do whatever you need to do here.
  }
}

On storyboard, from ViewController2 Ctrl+Drag from the button to the exit outlet and select doSomeStuffAfterReload.

You can see it in action here: https://spin.atomicobject.com/2014/10/25/ios-unwind-segues/ Happy coding^^