LoginSignup
12
9

More than 3 years have passed since last update.

Xcode11で作成したプロジェクトを古いOSに対応させる(完結編)

Last updated at Posted at 2019-07-06

以前、投稿した記事の続編です。
Xcode11で作成したプロジェクトを古いOSに対応させる(とりあえず版)
↑の対応をしておいてください。

UniversalアプリでiPhone用とiPad用でViewControllerを使い分けたいなど、
アプリ起動後に表示するViewControllerを自前で設定したい場合があります。

  1. 起動時にUIWindowを生成
  2. rootViewControllerをセット
  3. makeKeyAndVisible()する

iOS12まではapplication(_:didFinishLaunchingWithOptions:)で上記パターンのコードを書けばよかったのですが、iOS13では真っ黒な画面しか出てきません。:cold_sweat:

そこで、以下の対策を行いました。iOS13ではDark Modeも対応します。

  1. UIWindowの生成は各OSに応じて行う
      iOS12: AppDelegate
      iOS13: SceneDelegate

  2. 生成したUIWindowの設定を行うクラスメソッドを作成

AppDelegateでUIWindow生成 (iOS12以前用)

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    if #available(iOS 13.0, *) {
        // do nothing
    } else {
        window = UIWindow()
        AppDelegate.setupWindow(window!)
    }

    return true
}

SceneDelegateでUIWindow生成 (iOS13 onward用)

SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }

    window = UIWindow(windowScene: windowScene)
    AppDelegate.setupWindow(window!)
}

UIWindowを設定するクラスメソッドを追加

AppDelegate.swift
/// Sets up the window.
///
/// - Parameter window: Window that become key window with the root view controller.
class func setupWindow(_ window: UIWindow) {

    // position and size
    window.frame = UIScreen.main.bounds

    // root viewcontroller
    let viewController: UIViewController
    if UIDevice.current.userInterfaceIdiom == .phone {
        viewController = iPhoneViewController()
    } else {
        viewController = iPadViewController()
    }
    window.rootViewController = viewController

    // backgorund
    if #available(iOS 13.0, *) {
        window.backgroundColor = .systemBackground
    } else {
        window.backgroundColor = .white
    }

    window.makeKeyAndVisible()
}

Xcode 11 beta3を元に作成しています。後日変更される可能性があります。

12
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
9