gpt4 book ai didi

ios - SwiftUI - 如何在 SwiftUI 中弹出特定 View ?

转载 作者:行者123 更新时间:2023-12-05 07:17:29 26 4
gpt4 key购买 nike

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

View1 -> View2 -> View3 -> View4

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

最佳答案

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)

希望对你有帮助。

关于ios - SwiftUI - 如何在 SwiftUI 中弹出特定 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58813181/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com