Would like to return to my presenting UIKit View Controller after pressing the back button on my SwiftUI View (presented via a HostingViewController) and present the full view.
This is for UIKit viewcontroller
let chooseProfileView = ChooseProfileView()
// Wrap the SwiftUI view in a UIHostingController
let hostingController = UIHostingController(rootView: chooseProfileView)
hostingController.modalPresentationStyle = .fullScreen
// Present the UIHostingController modally
self.present(hostingController, animated: true, completion: nil)
The dismiss
environment value supports dismissing to a UIKit view controller too.
For example, here is a view with a back button:
struct SomeSwiftUIView: View {
@Environment(.dismiss) var dismiss
var body: some View {
VStack {
Text("This is a SwiftUI View")
Button("Back") {
dismiss()
}
}
}
}
You can present it from UIKit like this:
let swiftUIView = SomeSwiftUIView()
let hostingController = UIHostingController(rootView: swiftUIView)
hostingController.modalPresentationStyle = .fullScreen
self.present(hostingController, animated: true, completion: nil)
and pressing the back button will dismiss it as expected.
presentationMode environment value supports dismiss the SwiftUI view.
For example, here is a view with a back button:
its support for iOS 14.0 and above
struct ChooseProfileView: View {
@SwiftUI.Environment(.presentationMode) var presentationMode
var body: some View {
VStack {
Text("This is a SwiftUI View")
Button(action: {
presentationMode.wrappedValue.dismiss()
}) {
Image("HomeScreenBackButton")
.foregroundColor(.white)
.imageScale(.large)
}
}
}
}
Note:: It supports iOS 15.0 and higher – use this code
@Environment(.dismiss) var dismiss