LoginSignup
2
2

More than 1 year has passed since last update.

【SwiftUI】ViewController でSwiftUIを使う方法

Posted at

ViewController内でSwiftUIで構成したViewを使う

ViewController内でSwiftUIのViewを使用したい場合は、以下のように、SwiftUIのViewをUIHostingControllerでラップして使用できるようになります。

import SwiftUI

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // UIHostingViewControllerでSwiftUIのViewをラップする
        let vc: UIHostingController = UIHostingController(rootView: SampleView())
        // UIHostingViewControllerを子要素に追加
        self.addChild(vc)
        // UIHostingViewControllerのViewを追加
        self.view.addSubview(vc.view)
        // ViewControllerに処理が終了したことを伝える
        vc.didMove(toParent: self)
    }
}

struct SampleView : View {
    var body: some View {
        Text("SampleView")
    }
}

2
2
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
2
2