【问题标题】:SwiftUI - How you can pop to specific view in SwiftUI?SwiftUI - 如何在 SwiftUI 中弹出到特定视图?
【发布时间】:2019-11-12 06:29:09
【问题描述】:

有没有办法在 SwiftUI 中实现 popToViewController(vc) 等价物?例如,如果我有以下流程:

视图1 -> 视图2 -> 视图3 -> 视图4

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

【问题讨论】:

标签: ios swift uinavigationcontroller swiftui


【解决方案1】:
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)

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2022-06-17
    • 2022-06-23
    • 1970-01-01
    • 2022-10-15
    • 2020-01-02
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多