Skip to content

Instantly share code, notes, and snippets.

@eduardocoelho
Created February 27, 2013 02:23
Show Gist options
  • Save eduardocoelho/5044439 to your computer and use it in GitHub Desktop.
Save eduardocoelho/5044439 to your computer and use it in GitHub Desktop.
UIViewController abstract baseclass for registering/unregistering for C# events according to the UIViewController's life-cycle. Refs: - http://stackoverflow.com/questions/15076905/weak-event-pattern-in-monotouch - http://stackoverflow.com/questions/1816614/viewwilldisappear-determine-whether-view-controller-is-being-popped-or-is-showi
namespace BaseViewController
{
public abstract class BaseViewController : ViewController
{
#region Actions / Events handling
protected abstract void RegisterForActionsAndEvents ();
protected abstract void UnregisterForActionsAndEvents ();
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
if (!registeredForActionsAndEvents) {
RegisterForActionsAndEvents ();
registeredForActionsAndEvents = true;
}
}
public override void ViewWillDisappear (bool animated)
{
base.ViewWillDisappear (animated);
bool shouldUnregister = false;
if (registeredForActionsAndEvents) {
if (NavigationController != null) {
List<UIViewController> viewControllers = NavigationController.ViewControllers.ToList ();
if (!viewControllers.Contains (this)) {
// View is disappearing because it was popped from the navigation stack
shouldUnregister = true;
} else if (viewControllers.Count == 1 && PresentedViewController == null) {
// View is disappearing because the whole navigation stack is being removed
shouldUnregister = true;
}
} else {
// View is disappearing (without being contained in a navigation stack)
shouldUnregister = true;
}
}
if (shouldUnregister) {
UnregisterForActionsAndEvents ();
registeredForActionsAndEvents = false;
}
}
bool registeredForActionsAndEvents;
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment