我已经为按钮和textField创建了单独的视图。当我点击按钮时,我应该检查textField是否为空,如果不为空,我应该导航到下一页。在这里,我对基于场景管理navigationDestination感到惊讶。
class UserProgress: ObservableObject {
@Published var value = ""
@Published var flag = false
}
struct ButtonView: View {
@StateObject var progress = UserProgress()
var body: some View {
Button("Button title") {
print("Button tapped! \(progress.value.count)")
progress.flag = true
}
}
}
struct TextView: View {
@Binding var textValue: String
@ObservedObject var progress: UserProgress
var body: some View {
VStack {
TextField("Hello", text: $textValue)
.onChange(of: textValue) {
progress.value = $0
}
}
}
}
struct mainViewApp: View {
@StateObject var progress = UserProgress()
@State var readyToNavigate: Bool = false
@State var text1Value = ""
@State var text2Value = ""
var body: some View {
NavigationStack {
ZStack {
VStack {
VStack {
Text("Your value is \(progress.value)")
TextView(textValue: $text1Value, progress: progress)
if (progress.flag && text1Value.isEmpty) {
Text("ERROR1")
}
TextView(textValue: $text2Value, progress: progress)
if (progress.flag && text2Value.isEmpty) {
Text("ERROR2")
}
ButtonView(progress: progress)
}
}
}
.padding()
.navigationBarTitle("Main Menu", displayMode: .inline)
.navigationDestination(isPresented: $readyToNavigate) {
Text("Hello test2")
}
.toolbarColorScheme(.dark, for: .navigationBar)
.toolbarBackground(
Color.black,
for: .navigationBar)
.toolbarBackground(.visible, for: .navigationBar)
}
}
}
struct test_Previews: PreviewProvider {
static var previews: some View {
mainViewApp()
}
}
在这里我尝试管理它的可观察性,但无法在我正在检查的条件内更新readyToNavigate的状态值。
1条答案
按热度按时间v8wbuo2f1#
这是处理
viewmodel