skip to Main Content

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

I mean to say instead of this line self.presentationMode.wrappedValue.dismiss() is there any method to pass view controller to pop back

2

Answers


  1. 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)
        
        }
    
    Login or Signup to reply.
  2. @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) 
          }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search