我正在使用Xamarin.iOS的故事板.DashboardViewController(一个UINavigationController)被设置为故事板中的初始视图.但是,在我的AppDelegate类中,FinishedLaunching方法有条件地检查用户是否需要在应用程序启动时登录.如果是这样,它会将"ViewController"(登录控制器)设置为RootViewController,否则它将实例化由故事板设置的初始视图控制器,即"DashboardViewController".这是FinishedLaunching方法的代码.
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method Window = new UIWindow(UIScreen.MainScreen.Bounds); var storyboard = UIStoryboard.FromName("Main", NSBundle.MainBundle); bool isLoggedOut = true; UIViewController rootViewController; if (isLoggedOut) rootViewController = (UIViewController)storyboard.InstantiateViewController("ViewController"); else rootViewController = (UIViewController)storyboard.InstantiateInitialViewController(); Window.RootViewController = rootViewController; Window.MakeKeyAndVisible(); }
验证用户的凭据后,以下代码会尝试将RootViewController再次设置回原始的"DashboardViewController"并显示该视图.这是从登录控制器完成的.
partial void LoginBtn_TouchUpInside (UIButton sender) { var appDelegate = UIApplication.SharedApplication.Delegate as AppDelegate; appDelegate.SetRootViewController (dashboardViewController, true); this.PresentViewController (dashboardViewController, true, null); }
以下是AppDelegate中"SetRootViewController"的代码:
public void SetRootViewController() { Window = new UIWindow(UIScreen.MainScreen.Bounds); var storyboard = UIStoryboard.FromName("Main", NSBundle.MainBundle); bool isLoggedOut = false; UIViewController rootViewController; if (isLoggedOut) rootViewController = (UIViewController)storyboard.InstantiateViewController ("ViewController"); else rootViewController = (UIViewController)storyboard.InstantiateViewController (viewController); Window.RootViewController = rootViewController; Window.MakeKeyAndVisible(); }
到目前为止,这是有效的,但如果我尝试在DashboardViewController(这是一个UINavigationController)中向堆栈中添加另一个视图,请使用以下代码从按钮单击,
partial void ProfileBtn_TouchUpInside (UIButton sender) { this.NavigationController.PushViewController (profileViewController, true); }
NavigationController为null,应用程序崩溃.因此,此场景的基本流程是"将RootViewController设置为"ViewController",以便用户可以登录 - >当用户登录时,将RootViewController设置回DashboardViewController并显示该视图 - >单击按钮导航到另一个从DashboardViewController视图查看,但DashboardViewController中的NavigationController为null.
我究竟做错了什么??任何帮助或建议将不胜感激(我为长期问题道歉).
我已决定将这个问题留给那些可能遇到同样问题的人.我已经找到了我认为的解决方案.在我的AppDelegate"SetRootViewController"方法中,而不是说,
Window.RootViewController = rootViewController;
我需要说,
Window.RootViewController = new UINavigationController(rootViewController);
其他一切都保持不变.工作流程现在按预期工作.这是因为我试图设置为RootViewController的控制器不仅仅是一个UIViewController,它是一个由UINavigationController包装的UIViewController.这个答案也在以下链接中重申
https://forums.xamarin.com/discussion/23424/how-can-i-use-this-navigationcontroller-on-my-view
我为回答我自己的问题而道歉,如果有人有更好的方法或者看到有问题,请告诉我.希望这可以帮助将来的某个人.