我在 SwiftUI 中面临挑战,希望得到一些指导。在我的代码中,我正在使用
NavigationPath()
对象,并且需要从堆栈中获取最后两项。具体来说,此操作应该发生在名为 SomeView
的视图中,该视图位于导航堆栈深处。
在
Button
内的SomeView
的动作闭包内,我想将navigationControl.path
的最后两项分配给let常量(如果它们存在)。
我已经搜索了各种来源来寻找解决方案,但不幸的是,我还没有找到符合我要求的解决方案。至关重要的是,最后两项是从环境中检索的
navigationControl
变量获得的。虽然我知道这些项目可以通过在父视图实例化期间将它们注入 SomeView
来获得,但这种方法在我的情况下是不可接受的。
为了提供该项目的全面概述,我还附加了其他文件中的相关代码片段。
// SomeView.swift
import SwiftUI
struct SomeView: View {
@Environment(NavigationControl.self) private var navigationControl: NavigationControl
var body: some View {
Button("Tap to get the last two items in NavigationStack") {
// Not sure what to write here.
// It must be something like the following options just to illustrate what is desired:
// let lastItem = navigationControl.path.last()
// let lastItem = navigationControl.path[navigationControl.path.count]
// However, neither of them are defined.
// Note that only the last item assignemnt is shown here. However, it is desired to get the last two items from path.
}
}
}
#Preview {
NavigationStack {
SomeView()
.environment(NavigationControl())
}
}
// NavigationControl.swift
import SwiftUI
@Observable class NavigationControl {
var path = NavigationPath()
}
// ContentView.swift
import SwiftUI
struct ContentView: View {
@Environment(NavigationControl.self) private var navigationControl: NavigationControl
var body: some View {
@Bindable var navigationControl = navigationControl
NavigationStack(path: $navigationControl.path)
{
Button("Navigate") {
for i in 1..<5 {
navigationControl.path.append(i)
}
}
.navigationTitle("Root View")
.navigationDestination(for: Int.self) { number in
SomeView()
}
}
}
}
#Preview {
NavigationStack {
ContentView()
.environment(NavigationControl())
}
}
// NavigationPathLastElementApp.swift
import SwiftUI
@main
struct NavigationPathLastElementApp: App {
@State var navigationControl = NavigationControl()
var body: some Scene {
WindowGroup {
ContentView()
.environment(navigationControl)
}
}
}
任何有关如何实现这一目标的见解或建议将不胜感激。非常感谢您的帮助!
从 NavigationPath 中获取甚至一项都不可能,而您想要最多两项。这是一个死胡同——考虑其他方法。