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

Posted

技术标签:

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

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

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

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

【问题讨论】:

popTo 和 popToRoot 现在不可用。您可以参考***.com/a/57513566/1930006 并找到一些解决方法 也许@Enviroment 变量有帮助。 看看这个问题***.com/q/57700532/1291872我为SwiftUI创建了一个开源导航堆栈(github.com/biobeats/swiftui-navigation-stack),你可以用它来弹出到一个特定的视图。 【参考方案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)

希望对你有所帮助。

【讨论】:

以上是关于SwiftUI - 如何在 SwiftUI 中弹出到特定视图?的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI超便捷在iOS16中弹出App用户评价(Review)小窗口

SwiftUI超便捷在iOS16中弹出App用户评价(Review)小窗口

SwiftUI弹出自定义popup视图被NavigationView顶部的导航栏遮挡的解决

SwiftUI button 与sheet的使用

Sheet弹出视图在SwiftUI中“怪异”行为的解决(第一次弹出视图的可选属性总得到nil值)

Sheet弹出视图在SwiftUI中“怪异”行为的解决(第一次弹出视图的可选属性总得到nil值)