SceneDelegate 時代にコードだけで iOS アプリを実装し始める手順

iOS 13 で SceneDelegate が導入されて、Storyboard を使わずコードだけで iOS アプリを開発し始める手順が変わっていたのでメモ。

まず、メインインタフェースを空にする。これは以前と同じ。

f:id:griefworker:20210214213822p:plain

Info.plist の UISceneStoryboardFile を削除。

f:id:griefworker:20210214213838p:plain

SceneDelegate にウィンドウを表示する処理を記述。以前は AppDelegate に書いていたものが、こっちに移動してきた感じ。

using Foundation;
using UIKit;

namespace HelloSceneDelegate
{
    public class Application
    {
        static void Main(string[] args)
        {
            UIApplication.Main(args, null, "AppDelegate");
        }
    }

    [Register("SceneDelegate")]
    public class SceneDelegate : UIResponder, IUIWindowSceneDelegate
    {
        [Export("window")]
        public UIWindow Window { get; set; }

        [Export("scene:willConnectToSession:options:")]
        public void WillConnect(UIScene scene, UISceneSession session, UISceneConnectionOptions connectionOptions)
        {
            if (scene is  UIWindowScene windowScene)
            {
                var window = new UIWindow(windowScene: windowScene);
                Window = window;
                window.RootViewController = new UINavigationController(
                    new UIViewController
                    {
                        Title = "HelloSceneDelegate",
                    });
                window.MakeKeyAndVisible();
            }
        }

        [Export("sceneDidDisconnect:")]
        public void DidDisconnect(UIScene scene)
        {
        }

        [Export("sceneDidBecomeActive:")]
        public void DidBecomeActive(UIScene scene)
        {
        }

        [Export("sceneWillResignActive:")]
        public void WillResignActive(UIScene scene)
        {
        }

        [Export("sceneWillEnterForeground:")]
        public void WillEnterForeground(UIScene scene)
        {
        }

        [Export("sceneDidEnterBackground:")]
        public void DidEnterBackground(UIScene scene)
        {
        }
    }

    [Register("AppDelegate")]
    public class AppDelegate : UIResponder, IUIApplicationDelegate
    {

        [Export("window")]
        public UIWindow Window { get; set; }

        [Export("application:didFinishLaunchingWithOptions:")]
        public bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            return true;
        }

        // UISceneSession Lifecycle

        [Export("application:configurationForConnectingSceneSession:options:")]
        public UISceneConfiguration GetConfiguration(UIApplication application, UISceneSession connectingSceneSession, UISceneConnectionOptions options)
        {
            return UISceneConfiguration.Create("Default Configuration", connectingSceneSession.Role);
        }

        [Export("application:didDiscardSceneSessions:")]
        public void DidDiscardSceneSessions(UIApplication application, NSSet<UISceneSession> sceneSessions)
        {
        }
    }
}