LoginSignup
1
1

More than 1 year has passed since last update.

UIHostingControllerをpresentしてdismissする

Posted at

まだまだ移行期なので、UIKitな画面からSwiftUIなViewを表示したい時があるのでメモ。

TestView.swift
struct TestView: View {

    var dismiss: (() -> Void)?

    var body: some View {
        NavigationView {
            Text("Test View")
            .navigationTitle("List Navigation Sample")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading, content: {
                    closeButton {
                        dismiss?()
                    }
                })
            }
        }
    }

    private func closeButton(_ action: @escaping () -> Void) -> some View {
        Button(action: action) {
            Image(systemName: "xmark")
        }
        .foregroundColor(.black)
    }
}
TestHostingController.swift
final class TestHostingController: UIHostingController<TestView> {

    init() {
        super.init(rootView: TestView())
        rootView.dismiss = { [weak self] in // ← rootView経由でハンドラを設定するのがポイント
            self?.dismiss(animated: true)
        }
    }

    @MainActor required dynamic init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
SomeViewController.swift
// 表示する側のサンプルコード
let hosting = TestHostingController()
hosting.modalPresentationStyle = .fullScreen
navigationController?.present(hosting, animated: true)

もちろんpushも可能。
modalだと、以降のナビゲーションをSwiftUIで書けるので良いかもしれない。

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