11
10

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 5 years have passed since last update.

SwiftUIのViewをStoryboardで使用する方法とUIHostingControllerのライフサイクルについて

Posted at

SwiftUIで作ったViewをStoryboardで使用する

UIHostingControllerを継承したクラスを作成して

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder, rootView: ContentView())
}

このように初期化時にSwiftUIのViewをrootViewに指定します。

全体のコードです

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

class ContentViewHostingController: UIHostingController<ContentView> {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder, rootView: ContentView())

    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }
}

呼び出しは通常のSotryboardからの初期化と同じです。

let vc = UIStoryboard(name: "ContentViewHostingController", bundle: nil).instantiateViewController(identifier: "ContentViewHostingController")

(補足) UIHostingControllerのライフサイクルについて

バグなのか仕様なのかはわかりませんが、
SwiftUIのViewからコードでContentViewHostingControllerへ遷移させたところ viewDidLoad が呼ばれませんでした。
上記のようにStoryboardからの呼び出しであれば viewDidLoad が呼ばれたので補足として書いておきます。

11
10
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
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?