Search code examples
c#objective-ciosxamarin.iosuiapplicationdelegate

Get reference to UINavigationController


I have a rootcontroller pushed on a UINavigationController. Inside that rootcontroller class, I can access the UINavigationController with this.NavigationController

However, this rootcontroller has a ScrollView and I'm adding subcontrollers (or more precise, the View of this subcontroller) to this ScrollView.

I would now like to access the UINavigationController from inside such subcontroller. Following properties are all null

        this.NavigationController
        this.ParentViewController
        this.PresentedViewController
        this.PresentingViewController

It seems in ObjectiveC you can use following code

YourAppDelegate *del = (YourAppDelegate *)[UIApplication sharedApplication].delegate;
[del.navigationController pushViewController:nextViewController animated:YES];

Unfortunately, i don't know how to map this to C# in MonoTouch. I tried the following, but it's not working:

UIApplication.SharedApplication.KeyWindow.RootViewController.NavigationController

I know I could pass the UINavigationController object to all my classes (parameter in constructor), but that's probably not the cleanest way to go.


Solution

  • To extend poupou's answer, here is an example of what I usually do in my AppDelegate class:

    Add a static property of the AppDelegate itself:

    public static AppDelegate Self { get; private set; }
    

    Add my root navigation controller as a property:

    public UINavigationController MainNavController { get; private set; }
    

    In FinishedLaunching:

    Self = this;
    window = new UIWindow(UIScreen.MainScreen.Bounds);
    this.MainNavController = new UINavigationController(); // pass the nav controller's root controller in the constructor
    window.RootViewController = this.MainNavController;
    // ..
    

    This way, I can access the root view controller from anywhere, like this:

    AppDelegate.Self.MainNavController.PushViewController(someViewController);
    

    ... instead of having to write this all the time:

    AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
    myAppDelegate.MainNavController.PushViewController(someViewController);
    

    Plus, I can directly access all other AppDelegate's properties I might have.

    Hope this helps.