更改 RootView 控制器 Xamarin IOS 应用程序

Changing RootView controller Xamarin IOS app

我的 Xamarin IOS 项目使用 Storyboard。它是一个 tabbarcontroller 应用程序,我想修改我的根 UITabBarController 中的选项卡数量。

如果从情节提要中创建 tabbarcontroller,则无法添加或删除选项卡。我想用一个不是从 Storyboard 创建的视图控制器替换根视图控制器。我仍然喜欢其他一些 类.

的情节提要

在 Mac 上使用 Visual Studio 创建空 Xamarin 项目或从 Xamarin 项目中删除 Storyboard 的说明不起作用。

我认为新的 SceneDelegate 移除了在 AppDelegate 中设置根视图控制器的能力。

谢谢, 格里

实际上,您不需要删除 Storyboard。如果要在 AppDelegate 中设置 RootViewController ,请检查以下代码。

在 Appdelegate 中

以下代码将在 iOS 13.0

之前运行
public 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

   this.Window = new UIWindow(UIScreen.MainScreen.Bounds);
   var MainViewController = new MyViewController();
   this.Window.RootViewController = MainViewController;
   this.Window.MakeKeyAndVisible();

   return true;
}

而在iOS 13.0之后,我们要调用SceneDelegate中类似的代码,所以在SceneDelegate中同时添加如下代码。

public void WillConnect (UIScene scene, UISceneSession session, UISceneConnectionOptions connectionOptions)
{
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.

    this.Window = new UIWindow(new UIWindowScene(session,connectionOptions));
    var MainViewController = new MyViewController();
    this.Window.RootViewController = MainViewController;
    this.Window.MakeKeyAndVisible();

    // This delegate does not imply the connecting scene or session are new (see  UIApplicationDelegate `GetConfiguration` instead).
}

此外,如果您想在 运行 时间内更改 RootViewController(例如单击按钮时)。

我们使用了动画来使过程流畅

var MainController = new UITabBarController();
CATransition transition = CATransition.CreateAnimation();
transition.Duration = 0.3;
transition.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut);

UIApplication.SharedApplication.KeyWindow.RootViewController = MainController;
UIApplication.SharedApplication.KeyWindow.Layer.AddAnimation(transition, "Animation");