calling a parent UIViewController method from a child UIViewController
One easy way to achieve this you can use NSNotificationCenter
for that.
In your ParentViewController
add this into viewDidLoad
method:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: Selector(("refresh:")), name:NSNotification.Name(rawValue: "refresh"), object: nil)
}
After that add this function in ParentViewController
which will get called when you dismiss your ChildViewController
:
func refreshList(notification: NSNotification){
print("parent method is called")
}
and into your ChildViewController
add this code where you dismissing your child view:
@IBAction func btnPressed(sender: AnyObject) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil)
self.dismiss(animated: true, completion: nil)
}
Now when you dismiss child view refreshList
method will be call.
Add a weak property to the child view controller that should contain a reference to the parent view controller
class ChildViewController: UIViewController {
weak var parentViewController: UIViewController?
....
}
Then in your code (I'm assuming it's inside your parent view controller),
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("myChildView") as! ChildViewController
vc.parentViewController = self
self.presentViewController(vc, animated: true, completion: nil)
And, as vomako said, call the parent's method before dismissing your child view controller.
parentViewController.someMethod()
self.dismissViewControllerAnimated(true, completion: nil)
Or, you can also call the method in the completion paramter of dismissViewControllerAnimated, where it will be run after you child view controller dismisses:
self.dismissViewControllerAnimated(true) {
parentViewController.someMethod()
}