我一直在使用 SwiftUI 并遇到了意外的行为。
我有视图 A 和视图 B 和视图 C。视图 C 具有从视图 A 更改 AppState 的 EnviromentObject
视图 B 具有带有选择的 ViewModel
如果我从 ViewModel 调用函数来更改选择,则视图 C 会显示几秒钟,然后它会自动弹回视图 B
如果我直接从视图 B(而不是视图模型)更改选择,一切都会按预期工作。另外,如果我注释掉Dissapear,它也可以工作。但是,当屏幕消失时我需要更改 environmentObject 这是 View B 和 ViewModel
import SwiftUI
class AppState: ObservableObject {
@Published
var shouldHideUserInfo = false
}
struct ContentView: View {
@EnvironmentObject
var appState: AppState
@State
var selection: Int? = nil
var body: some View {
NavigationView {
VStack {
if !appState.shouldHideUserInfo {
Text("USER INFO")
}
NavigationLink(
destination: ViewA(),
tag: 1,
selection: $selection,
label: { EmptyView()})
Button("MOVE TO VIEW A") {
selection = 1
}
}
}
}
}
class ViewAModel: ObservableObject {
@Published
var selection: Int? = nil
func navigate() {
selection = 2 //<- this doesnt
}
}
struct ViewA: View {
@ObservedObject
var viewModel: ViewAModel
init() {
viewModel = ViewAModel()
}
@State
var selection: Int? = nil //<- this works
var body: some View {
VStack
{
Text("VIEW A")
NavigationLink(
destination: ViewB(),
tag: 2,
selection: $viewModel.selection,
label: { EmptyView()})
Button("MOVE TO VIEW B") {
//selection = 2 <-- this works
viewModel.navigate() //<- this doesnt
}
}
}
}
struct ViewB: View {
@EnvironmentObject
var appState: AppState
@State
var selection: Int? = nil
var body: some View {
VStack
{
Text("VIEW B")
}
.onAppear {
appState.shouldHideUserInfo = true
}
}
}
工厂模式没有解决问题:
static func makeViewA(param: Int?) -> some View {
let viewModel = ViewAModel(param: param)
return ViewA(viewModel: viewModel)
}
}