UIViewControllerRepresentable
SwiftUI の世界で UIViewController を利用したい場合は、UIViewControllerRepresentable を利用する。
https://developer.apple.com/documentation/swiftui/uiviewcontrollerrepresentable
UIViewControllerRepresentable インスタンスは、UIViewController オブジェクトの生成/更新/破棄を制御する責務を持つ。SwiftUI によって各々のタイミングで適切なメソッドが呼び出されるので、必要な処理を用意してやれば良い。逆にUIViewController から SwiftUI 側に何か影響を及ぼしたい場合、その橋渡しのために Coordinator を利用する。
code:swift
public protocol UIViewControllerRepresentable : View where Self.Body == Never {
associatedtype UIViewControllerType : UIViewController
/// ViewController の初期化時に呼び出される
///
/// context を参照することで現在のアプリの状態に合わせて ViewController を初期化する
/// システムによって1度のみ呼び出され、初回以降は updateUIViewController が呼び出される
@MainActor func makeUIViewController(context: Self.Context) -> Self.UIViewControllerType
/// ViewController の状態を更新する
///
/// アプリの状態変化時に呼び出される
@MainActor func updateUIViewController(_ uiViewController: Self.UIViewControllerType, context: Self.Context)
/// ViewController の破棄時に呼び出される
@MainActor static func dismantleUIViewController(_ uiViewController: Self.UIViewControllerType, coordinator: Self.Coordinator)
associatedtype Coordinator = Void
/// Coordinatorを生成する
@MainActor func makeCoordinator() -> Self.Coordinator
@available(iOS 16.0, tvOS 16.0, *)
@MainActor func sizeThatFits(_ proposal: ProposedViewSize, uiViewController: Self.UIViewControllerType, context: Self.Context) -> CGSize?
/// システムの状態のコンテキスト
///
/// 以下を含む
/// - Coordinator オブジェクト
/// - アニメーションのための情報を保持した Transaction
/// - 環境設定を含んだ EnvironmentValues
typealias Context = UIViewControllerRepresentableContext<Self>
}