3

I have a fairly extensive project that I started with UIKit and now I've decided to use SwiftUI to make some simple form pages, but I need to make a button in SwiftUI to dismiss the current view which is presented with the following code:

   func goToSchedule() {
        let vc = UIHostingController(rootView: ScheduleView())
        if let topController = UIApplication.topViewController() {
            topController.present(vc, animated: true, completion: nil)
        }
    }
Watermamal
  • 357
  • 3
  • 12

2 Answers2

3

You can dismiss it by holding a reference to it. So hold vc in more public scope and dismiss it when you need to.

var vc: UIViewController

or something like this:

if let topController = UIApplication.topViewController() {
    topController.presentedViewController?.dismiss(animated: true)
}
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
1

If I correctly understood code snapshot then .topViewController() will be presented UIHostingViewConroller when ScheduleView shown, so it should inside it like

var body: some View {
    // ...
    // somewhere ...

    Button("Close") {
        if let topController = UIApplication.topViewController() {
            topController.dismiss(animated: true)
        }
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690