Search code examples
iosxcodeswift

Swift: Perform a function on ViewController after dismissing modal


A user is in a view controller which calls a modal. When self.dismissViewController is called on the modal, a function needs to be run on the initial view controller. This function also requires a variable passed from the modal.

This modal can be displayed from a number of view controllers, so the function cannot be directly called in a viewDidDisappear on the modal view.

How can this be accomplished in swift?


Solution

  • How about delegate?

    Or you can make a ViewController like this:

    typealias Action = (x: AnyObject) -> () // replace AnyObject to what you need
    class ViewController: UIViewController {
      func modalAction() -> Action {
        return { [unowned self] x in 
          // the x is what you want to passed by the modal viewcontroller
          // now you got it
        }
      }
    }
    

    And in modal:

    class ModalViewController: UIViewController {
      var callbackAction: Action?
       override func viewDidDisappear(_ animated: Bool) {
        let x = … // the x is what you pass to ViewController
        callbackAction?(x)
      }
    }
    

    Of course, when you show ModalViewController need to set callbackAction like this modal.callbackAction = modalAction() in ViewController