Watermamal
Watermamal

Reputation: 378

How to make a button that dismisses a view presented using UIHostingController/SwiftUI?

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)
        }
    }

Upvotes: 3

Views: 300

Answers (2)

Asperi
Asperi

Reputation: 258345

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)
        }
    }
}

Upvotes: 1

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119917

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)
}

Upvotes: 3

Related Questions