我有一个
NavigationView
,它有 3 个我想连续导航到的视图。每个视图中都有一个 NavigationLink
。理想情况下,我想要:
视图 1 -> 视图 2 -> 视图 3
但我得到的是:视图 1 -> 视图 2 -> 视图 3(1 秒) -> 视图 1
我对
NavigationLink
使用标记选择方法,并且选择来自 @Published
EnvironmentObject
。
这是代码:
import SwiftUI
struct ContentView: View {
@EnvironmentObject var viewModel: ViewModel
var body: some View {
VStack {
NavigationLink(destination: secondPage(), tag: "View 2", selection: $viewModel.selection) {
Button(
action: {
viewModel.selection = "View 2"
}, label: {
Text("view 2")
}
)
.navigationTitle("View 1")
}
.isDetailLink(false)
}
}
}
struct secondPage: View {
@EnvironmentObject var viewModel: ViewModel
var body: some View {
NavigationLink(destination: thirdPage(), tag: "View 3", selection: $viewModel.selection) {
Button(
action: {
viewModel.selection = "View 3"
},
label: {
Text("View 3")
}
)
.navigationTitle("View 2")
}
.isDetailLink(false)
}
}
struct thirdPage: View {
var body: some View {
VStack {
Text("third page")
}
.navigationTitle("View 3")
}
}
class ViewModel: ObservableObject {
@Published var selection: String? = nil
}
import SwiftUI
@main
struct testApp: App {
@StateObject var viewModel = ViewModel()
var body: some Scene {
WindowGroup {
NavigationView {
ContentView()
}
.navigationViewStyle(StackNavigationViewStyle())
.environmentObject(viewModel)
}
}
}
我使用按钮和 viewModel,因为在我的真实代码中我需要代码来执行操作。
非常感谢您的帮助!
您遇到的问题与这个问题非常相似,但您使用的是不同的机制。弹出的原因是您使用相同的变量来处理两个
NavigationLinks
,所以,而不是:
View 1 -> View 2 -> View 3
实际发生的事情是:
View 1(viewModel.selection = "View 2") -> View 2
然后,当您再次尝试导航时:
View 2(viewModel.selection = "View 3")
您实际上是将原始链接更改为
View 1(viewModel.selection = "View 3") -> View 2
还有。操作系统感到困惑并弹回到第一个链接(
SecondPage
)。要修复它,只需使用多个变量来保持导航状态即可:
struct ContentView: View {
@EnvironmentObject var viewModel: PageViewModel
var body: some View {
VStack {
NavigationLink(destination: secondPage(), tag: "View 2", selection: $viewModel.selection2) {
Button(
action: {
viewModel.selection2 = "View 2"
}, label: {
Text("view 2")
}
)
.navigationTitle("View 1")
}
.isDetailLink(false)
}
}
}
struct secondPage: View {
@EnvironmentObject var viewModel: PageViewModel
var body: some View {
NavigationLink(destination: thirdPage(), tag: "View 3", selection: $viewModel.selection3) {
Button(
action: {
viewModel.selection3 = "View 3"
},
label: {
Text("View 3")
}
)
.navigationTitle("View 2")
}
.isDetailLink(false)
}
}
struct thirdPage: View {
var body: some View {
VStack {
Text("third page")
}
.navigationTitle("View 3")
}
}
class PageViewModel: ObservableObject {
@Published var selection2: String? = nil
@Published var selection3: String? = nil
}