Way 1:
struct TestView: View {
var dismiss: (() -> Void)
var body: some View {
Button(action: dismiss) {
Text("Close")
}
}
}
func show() {
let view = TestView(dismiss: { self.navigationController.presentedViewController?.dismiss(animated: true) })
let vc = UIHostingController(rootView: view)
navigationController.present(vc, animated: true)
}
Way 2:
struct TestView: View {
var dismiss: (() -> Void)!
var body: some View {
Button(action: dismiss) {
Text("Close")
}
}
}
final class TestViewController: UIHostingController<TestView> {
init() {
super.init(rootView: TestView())
rootView.dismiss = dismiss
}
@objc required dynamic init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func dismiss() {
dismiss(animated: true, completion: nil)
}
}
func show() {
let vc = TestViewController()
navigationController.present(vc, animated: true)
}