swiftUIではviewというものが表示の構造体を意味していて、
そして通常のswiftではUIViewControllerがその役割をになっている。
しかし、swiftUIではviewがあくまで表示となっているので、viewconrtollerを使用することができません。
なのでViewControllerで作成した表示のコンテンツを、swiftUIでも使用できるようにするためには以下のコードが必要となります。
そして、一回viewControllerをswiftのviewに変換をしてしまえば、あとは通常のように使用すれば表示が可能となります。
しかしswiftUIもまだリリースされたばっかなので、どうしてもViewCOntrollerでできることがswiftUIではまだできないなどの違いがあります。
なのでviewControllerで表示して、そして変換をしてviewで表示吸えるというようなやり方が必要になってきます。
ViewController → SwiftUIのViewへの変換コード
import UIKit
import SwiftUI
/**
SwiftUIでViewControllerを表示する。
*/
struct aaa:View{
var body: some View{
VStack{
SampleViewControllerWrapper()
}
}
}
/**
SwiftUIでviewControllerを表示する際に必要なコード
*/
struct SampleViewControllerWrapper : UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> SampleViewController {
return SampleViewController()
}
func updateUIViewController(_ uiViewController: SampleViewController, context: Context) {
}
}
/**
従来のViewControllerでviewの作成
*/
class SampleViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label:UILabel = UILabel(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
label.text = "testSample"
self.view.backgroundColor = UIColor.green
self.view.addSubview(label)
}
}
● GeometryReader 続きを見る
【SwiftUI】GeometryReaderでViewのサイズを知ろう
● MVVM(Model-View-ViewModel) 続きを見る
【SwiftUI】SwiftUIをMVVMフレームワークで実装しよう