How to reliably detect that the UIViewController has been fired

I need to do things when the ViewController is rejected, i.e.

  • When you click "Back"
  • When popToRootViewController is called by parent if it was in UINavigationController
  • when the DismissViewController is called by the parent if it was presented

For example, I need to unsubscribe from events, or reduce an informed warning, etc.

ViewWillDisappear is not called when popToRootViewController is called by its parent, so it doesn't work.

WillMoveToParentViewController is only for protecting View Controller

Dealloc does not work as it is only for garbage collection. I am using C # Xamarin anyway and it doesn't work there.

ViewDidUnload is no longer used and has never been used for this

The ViewController itself shouldn't care how it was presented and how do we know when it is fired?

This seems like an important, basic requirement. How can we discard events from the model without this, for example?

This is a similar question, but there is no good answer:

Can you detect when UIViewController got fired or popped out?

+3


source to share


3 answers


This question is a little old, but here is the conclusion I have arrived at:

-dealloc - there is no guarantee of when this will be called. Good for templates, but not robust.

-viewDidDisappear and -viewWillDisappear are only called when the view is no longer visible (imagine that;)). So they are ok when you fetch one view at a time, but not popToRoot or return multiple controllers at a time



-willMoveToParentViewController should work (the viewControllers in the UINavigation controller are contained in that controller), but for some reason I see inconsistencies in when this is called or not.

-didMoveToParentViewController - Called on every viewController that is deviated from the navigation stack. So ... this looks like the safest place to do this.

+1


source


I called presentingViewController.viewWillAppear from my modal so that it knows it is being fired.



+1


source


When using a UINavigationController, it is available through the NavigationController property of a UIViewController (or equivalent) subclass.

ViewWillDisappear(bool animated)

and ViewDidDisappear(bool animated)

will be called when a new UIViewController is loaded onto the UINavigationController stack.

This might help if you are using storyboarding functionality in Xamarin Studio, since the visual representation of the NavigationController-> UIViewController.

If you have any problems, please post some sample code for the community to look further.

-1


source







All Articles