【发布时间】:2021-08-16 14:39:00
【问题描述】:
我正在尝试建立一个商店以便在 SwiftUI 流程中导航。 这个想法是每个屏幕都应该观察状态并使用 NavigationLink 进入下一个屏幕。
它似乎适用于推送一个视图,但是当我将几个视图推送到堆栈中时,它开始表现得很奇怪:视图会自行弹出。
幸运的是,我能够在一个单独的项目中重现它。当我从 2 移动到 3 时,会出现第三个屏幕,但 NavigationView 会重置为其原始状态 (ContentView):
import SwiftUI
@main
struct NavigationTestApp: App {
var body: some Scene {
WindowGroup {
NavigationView {
ContentView()
}.navigationViewStyle(StackNavigationViewStyle())
}
}
}
class Store: ObservableObject{
@Published var state: StoreState
struct StoreState {
var flowState: FlowState = .none
}
enum FlowState {
case none, one, two, three
}
enum Action {
case moveTo1, moveTo2, moveTo3
}
init(state: StoreState) {
self.state = state
}
func send(_ action: Action) {
switch action {
case .moveTo1:
state.flowState = .one
case .moveTo2:
state.flowState = .two
case .moveTo3:
state.flowState = .three
}
}
}
struct ContentView: View {
@ObservedObject var store = Store(state: .init())
var body: some View {
VStack {
Button(action: {
store.send(.moveTo1)
}, label: {
Text("moveTo1")
})
NavigationLink(
destination: ContentView1().environmentObject(store),
isActive: Binding(
get: { store.state.flowState == .one },
set: { _ in
}
),
label: {}
)
}
}
}
struct ContentView1: View {
@EnvironmentObject var store: Store
var body: some View {
VStack {
Button(action: {
store.send(.moveTo2)
}, label: {
Text("moveTo2")
})
NavigationLink(
destination: ContentView2().environmentObject(store),
isActive: Binding(
get: { store.state.flowState == .two },
set: { _ in
}
),
label: {}
)
}
}
}
struct ContentView2: View {
@EnvironmentObject var store: Store
var body: some View {
VStack {
Button(action: {
store.send(.moveTo3)
}, label: {
Text("moveTo3")
})
NavigationLink(
destination: ContentView3().environmentObject(store),
isActive: Binding(
get: { store.state.flowState == .three },
set: { _ in
}
),
label: {}
)
}
}
}
struct ContentView3: View {
@EnvironmentObject var store: Store
var body: some View {
Text("Hello, world!")
.padding()
}
}
我错过了什么?
【问题讨论】:
-
尝试使用
.isDetailLink(false),例如stackoverflow.com/a/61707193/12299030