Search code examples
iosswift2presentviewcontrollerviewwilldisappear

Trigger events when ViewController covered by a presented ViewController


I would like to process code when a ViewController is no longer visible due to presenting a new ViewController.

I cannot use ViewWillDisappear etc since the controller is not technically ever dismissed from the stack - you just can't see it.

What process can I use so that code runs when the controller is no longer visible (i.e. topmost) and when it becomes visible again?

EDIT: Seems some confusion here - not sure why. I have a viewcontroller. I use the following code to present another controller

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let navController = storyboard.instantiateViewControllerWithIdentifier("NavController") as! UINavigationController
let thisController = navController.viewControllers[0] as! MyController
self.presentViewController(navController, animated: true, completion: nil)

This controller does not trigger a viewWillDisappear on the previous controller since the previous view is not removed - just hidden.

I need to process code when this view is hidden (i.e. not visible) and, more importantly, process code when it becomes visible again.


Solution

  • When presenting a UIViewController if the presentation style has been set to UIModalPresentationOverCurrentContext it doesn't call the viewWillDisappear and related methods as the view never disappears or gets hidden.

    A simple test to check if thats the case would be to set the NavController that you are using to have a clear background color. If you do this and present the NavController and you can still view the first UIViewController below your NavController content. Then you are using UIModalPresentationOverCurrentContext and that is why the viewDidDisappear isn't called.

    Have a look at the answer referenced by Serghei Catraniuc (https://stackoverflow.com/a/30787112/4539192).