SwiftUI-如何在SwiftUI中弹出特定视图?

时间:2019-11-12 06:29:09

标签: ios swift uinavigationcontroller swiftui

是否有某种方法可以在SwiftUI中实现等效的popToViewController(vc)?例如,如果我有以下流程:

  

View1-> View2-> View3-> View4

考虑到我们无法控制导航堆栈,如何从View4直接弹出到View2?

1 个答案:

答案 0 :(得分: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)

希望能帮到你。