memyselfandi,有很多不同的概念要理解,你可以下一个断点来查看你的 rootViewController 的结构。为了在您的应用中的任何位置获取 RootViewController,您可以这样做:
var appDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;
var rootVC = appDelegate.Window.RootViewController;
如果您的 RootViewController 没有 UINavigationController,则有两种添加 ViewController 的方法:
- 您只能从 RootViewController 内部通过 PresentViewController 显示您的 UIViewController,因此它显示为模态,而其他视图可以在后台看到。正如您已经知道的那样,这只是像这样完成
PresentViewController(vc, true, null);
- 或者您可以用包含新 UIViewController 的 UINavigationController 替换 RootViewController。然后继续将内容推送到 NavigationController 堆栈。这将防止其他视图留在后台。
var navController = new UINavigationController(vc);
// where, vc is the ViewController you want to replace the existing one with.
// Eg: think of situations where you login a user.
rootVC = navController;
奖励:当您将 viewControllers 以奇怪的方式堆叠在其他 viewControllers 之上时,它会变得有点复杂,因此您可以通过以下方式传递您的 viewController:
public static void Push(UIViewController vc)
{
// to get the RootViewController, we have to get it from the AppDelegate
var appDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;
var rootVC = appDelegate.Window.RootViewController;
// If you want to push to a ModalViewController which consists of a NavigationController
if (rootVC.PresentedViewController != null && rootVC.PresentedViewController.NavigationController != null)
rootVC.PresentedViewController.NavigationController.PushViewController(vc, true);
// If there already is a NavigationController, you can do a simple push
else if (rootVC.NavigationController != null)
rootVC.NavigationController.PushViewController(vc, true);
// If the NavigationController exists in a TabBar, we have to push on that
else if (rootVC != null
&& rootVC is UITabBarController tabbarController
&& tabbarController.SelectedViewController is UINavigationController navigationController)
navigationController.PushViewController(vc, true);
// If all else fails, present the ViewController as a modal
else if (rootVC != null)
rootVC.PresentViewController(vc, true, null);
}