UIViewRepresentableとUIHostingController

UIViewRepresentable

SwiftUIの中で、UIKitのViewを使用したい時に継承します。

  • makeUIView(context:)
  • updateUIView(_:context:)

この2つの関数を呼ぶことで、Viewの実装を完結することができます。 makeUIView(context:)は、viewの初期化 updateUIView(_:context:)は、layout を決める時に使用しています。

struct MapView: UIViewRepresentable {
    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }
    
    func updateUIView(_ view: MKMapView, context: Context) {
        let coordinate = CLLocationCoordinate2D(
            latitude: 34.011286, longitude: -116.166868)
        let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        view.setRegion(region, animated: true)
    }
}

SwiftUIのチュートリアルでは、MapViewにUIViewRepresentableを継承させました。 このように継承させることにより、

struct ContentView: View {
    var body: some View {
        VStack {
            MapView()
                .edgesIgnoringSafeArea(.top)
                .frame(height: 300)
        }
    }
}

上のように、SwiftUIの中で、UIKitのコンポーネントを使用することができます。

UIHostingController

UIKitをメインにSwiftUIを用いたい時にUIHostingController を使用します。

let viewController = UIHostingController(rootView:  ContentView)

struct ContentView: View {
    var body: some View {
           Text("Joshua Tree National Park")
    }
}

1つのViewControllerとして扱えるようになるようです。