I have three controllers and one swiftUI view, below is the flow
A Controller(RootController) -> B controller - > C controller -> SwiftUI view
I am doing some operation on the SwiftUI view based on the operation need to decide to whether pop back to C controller or B. Currently I am able pop back to C Controller and root controller, not sure how to jump to specific (in my case B controller)controller in SwiftUI
.navigationBarItems(leading:Button(action: {
self.presentationMode.wrappedValue.dismiss()
})
CodePudding user response:
You can make an extension for UINavigationController
extension UINavigationController {
func popToViewController(ofClass: AnyClass, animated: Bool = true) {
if let vc = viewControllers.last(where: { $0.isKind(of: ofClass) }) {
popToViewController(vc, animated: animated)
}
}
}
and use it like this
func goBack() {
navigationController?.popToViewController(ofClass: UIHostingController<SomeSwinftUIView>.self) // if this is a swuftUI view
}
or
func goBack() {
navigationController?.popToViewController(ofClass: SomeViewController.self)
}
CodePudding user response:
@OhStack just import UIKit (Personally i'm using a router/coordinator for navigation, and there I include UIKit)
import UIKit
import SwiftUI
struct SwiftUIViewCoordinator {
let navController: UINavigationController?
func startView(navController: UINavigationController) {
self.navController = navController
let swiftUIView = SwifUIViewView(router: self)
let hostingView = UIHostingController(rootView: swiftUIView)
navigationController?.pushViewController(hostingView, animated: true)
}
func goBackToSomeView() {
navigationController?.popToViewController(ofClass:
UIHostingController<SomeSwinftUIView>.self)
}
}