2

Is there some way to implement popToViewController(vc) equivalent in SwiftUI? For example if I have the following flow:

View1 -> View2 -> View3 -> View4

How can I pop from View4 directly to View2 considering that we do not have control over the navigation stack ?

  • 1
    popTo and popToRoot is not available now. You may refer https://stackoverflow.com/a/57513566/1930006 and find some workarounds – Alfred Woo Nov 12 '19 at 07:11
  • Maybe @Enviroment variable helps. – Mojtaba Hosseini Nov 12 '19 at 20:39
  • Take a look at this question https://stackoverflow.com/q/57700532/1291872 I created an open source navigation stack for SwiftUI (https://github.com/biobeats/swiftui-navigation-stack), you can use it to pop to a specific view. – matteopuc Feb 04 '20 at 12:08

1 Answers1

0
Hello **@Milen Valchev**, I'm new to SwiftUI. As I'm doing R&D on some functionaities with SwiftUI. I'm facing issue with PopToSpecific View. After R&D I got something. You can use this for PopToSpecific View.

**1. First you've to create a extension for UINavigationController. check this below mentioned code**


import UIKit

extension UINavigationController {
    
    func popToViewController(ofClass: AnyClass, animated: Bool = true) {
        if let vc = viewControllers.filter({$0.isKind(of: ofClass)}).last {
            popToViewController(vc, animated: animated)
        }
    }
    
    func popViewControllers(viewsToPop: Int, animated: Bool = true) {
        if viewControllers.count > viewsToPop {
            let vc = viewControllers[viewControllers.count - viewsToPop - 1]
            popToViewController(vc, animated: animated)
        }
    }
    
    func popBack<T: UIViewController>(toControllerType: T.Type) {
        if var viewControllers: [UIViewController] = self.navigationController?.viewControllers {
            viewControllers = viewControllers.reversed()
            for currentViewController in viewControllers {
                if currentViewController .isKind(of: toControllerType) {
                    self.navigationController?.popToViewController(currentViewController, animated: true)
                    break
                }
            }
        }
    }
}

**2. After creating UINavigationController extension you've to get UINavigationController instance by using this code.**


let window = UIApplication.shared.connectedScenes
            .filter { $0.activationState == .foregroundActive }
            .map { $0 as? UIWindowScene }
            .compactMap { $0 }
            .first?.windows
            .filter { $0.isKeyWindow }
            .first
        let navigation = window?.rootViewController?.children.first as? UINavigationController


**Note:- Once you get the UINavigationController instance you can easily PopToSpecific View.**

You can use this code.

navigation.popViewControllers(viewsToPop: 2)

Hopefully it'll help you.

V.Kumar
  • 109
  • 2
  • 4