'UIHostingController and navigationController
Default swift project with view controller embedded in navigationController and pushing to next UIHostingController.
How to call navigationController?.popViewController from SimpleView ?
ViewController:
@IBOutlet weak var button: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
button?.addTarget(self,
action: #selector(showNewSwiftUIController),
for: .touchUpInside)
}
@objc func showNewSwiftUIController() {
let vc = UIHostingController(rootView:SimpleView())
navigationController?.pushViewController(vc, animated: true)
}
SwiftUI:
struct SimpleView: View {
var body: some View {
Text("SimpleView")
.foregroundColor(.black)
}
}
Solution 1:[1]
First. Have you tried?
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> // reference
Then on your body call:
self.presentationMode.wrappedValue.dismiss()
If that does not work:
I will suggest you either pass the navigation controller as an optional variable into the View as a reference and access from there. Other option and maybe a healthier option is to pass a "callback" variable from the parent to the childView to dismiss the view (you need to save the Navigation as a variable to keep track)
Last option (Not recommended)
if var topController = UIApplication.shared.windows.first?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
topController.navigationController.popViewController(animated:true)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wilson Muñoz |