Alex Stefan Alex Stefan - 24 days ago 13
iOS Question

NavigationController is null

Can someone explain me why I get the NavigationController null everywhere I want to access it, even though the Presenter class from MvvmCross seems to initialise one?

Bellow is my current code, I tried multiple ways to get the NavigationController, but none of them worked.

The purpose of this is to hide it on the first screen of the app (Login).
How to achieve this?

AppDelegate.cs

[Register("AppDelegate")]
public class AppDelegate : MvxApplicationDelegate
{
private UIWindow window;

public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
window = new UIWindow(UIScreen.MainScreen.Bounds);
var presenter = new MvxIosViewPresenter(this, window);

var setup = new Setup(this, presenter);
setup.Initialize();

var startup = Mvx.Resolve<IMvxAppStart>();
startup.Start();

window.MakeKeyAndVisible();

return true;
}
}


LoginScreen.cs

public partial class LoginScreen : MvxViewController
{
private UITabBarController tabBarController;

public new LoginViewModel ViewModel
{
get { return (LoginViewModel)base.ViewModel; }
set { base.ViewModel = value; }
}

public LoginScreen()
{
NavigationController.SetToolbarHidden(true, false);

tabBarController = new UITabBarController();
tabBarController.View.Frame = new CGRect(0, 0, View.Bounds.Width, 450);

var tab1 = new UIViewController();
tab1.Title = "tab1";
tab1.View.BackgroundColor = UIColor.Green;
var tab2 = new UIViewController();
tab2.Title = "tab2";
tab2.View.BackgroundColor = UIColor.Orange;
var tab3 = new UIViewController();
tab3.Title = "tab3";
tab3.View.BackgroundColor = UIColor.Red;

tabBarController.ViewControllers = new UIViewController[] { tab1, tab2, tab3 };

var cgrect = new CGRect(0, 510, View.Bounds.Width, 45);
var button = new UIButton(UIButtonType.Custom)
{
BackgroundColor = UIColor.Green,
};
button.SetTitle("click", UIControlState.Normal);
button.Frame = cgrect;

View.AddSubviews(new UIView[] { tabBarController.View, button });

var swipeLeft = new UISwipeGestureRecognizer(HandleLeftSwipe)
{
Direction = UISwipeGestureRecognizerDirection.Left
};
var swipeRight = new UISwipeGestureRecognizer(HandleRightSwipe)
{
Direction = UISwipeGestureRecognizerDirection.Right
};
tabBarController.View.AddGestureRecognizer(swipeLeft);
tabBarController.View.AddGestureRecognizer(swipeRight);
}

Answer

The reason as to why the NavigationController property is null in your constructor, is because it is not attached to the UINavigationViewController at that point of the lifecycle.

You should preferably set up UI inside of an override of ViewDidLoad