0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[初級者向け]SwiftUIでrootViewをContentViewから任意のViewに変更しよう

Last updated at Posted at 2020-06-14

ContentViewから任意のViewに変更しよう

環境

  • Xcode11.5
  • Swift5
  • SwiftUI

この記事で何をしようとしているか

Xcodeから新規プロジェクトを作成後、デフォルトで設定されているContentViewを自分の好きなViewに変更したい。
例えば, ContentView -> RootView, LoginView等

Screen Shot 2020-06-14 at 18.12.25.png

1. 任意ファイルを作成

File > New > FileからSwiftUIを選択して、新しいファイルを作成します。今回はファイル名を"RootView"とします。

Screen Shot 2020-06-14 at 18.14.10.png

下図のようにRootView.swiftファイルが作成できたことが確認できます。
Screen Shot 2020-06-14 at 18.25.34.png

以下、作成したRootView.swiftのコード

RootView.swift
import SwiftUI

struct RootView: View {
    var body: some View {
        Text("Root View なんだぜ〜")
    }
}

struct RootView_Previews: PreviewProvider {
    static var previews: some View {
        RootView()
    }
}

2. SceneDelegate.swiftを編集

SceneDelegate.swift
import UIKit
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.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 delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
        // 以下、作成したViewを指定
        // let contentView = ContentView()
        let rootView = RootView()

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            // contentView -> rootView
            window.rootViewController = UIHostingController(rootView: rootView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

 // ...  以下、不要なので省略

}

3. シュミレータまたは実機で実行

下図のように、RootViewに変更できていることがわかります。
Screen Shot 2020-06-14 at 18.22.34.png

ついでに

本記事のように、新規ファイルを作成せず、ContentView.swiftファイルを編集することもできます。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?