我想在应用程序中有条件地显示不同的视图-如果某个布尔值为true,则将显示一个视图。如果为假,将显示其他视图。此布尔值在ObservableObject类内,并且从将要显示的视图之一中更改。
PracticeStatus.swift(父视图)
import Foundation
import SwiftUI
import Combine
class PracticeStatus: ObservableObject {
@Published var showResults:Bool = false
}
PracticeView.swift(父视图)
struct PracticeView: View {
@EnvironmentObject var practiceStatus: PracticeStatus
var body: some View {
VStack {
if practiceStatus.showResults {
ResultView()
} else {
QuestionView().environmentObject(PracticeStatus())
}
}
}
}
QuestionView.swift
struct QuestionView: View {
@EnvironmentObject var practiceStatus: PracticeStatus
var body: some View {
VStack {
...
Button(action: {
self.practiceStatus.showResults = true
}) { ... }
...
}
}
}
但是,此代码无效。当按下QuestionView
中的按钮时,不会显示ResultView。有人有解决方案吗?谢谢!
答案 0 :(得分:1)
您是否尝试过编译代码?有几个基本错误:
practice
在PracticeView
中不存在。您是说practiceStatus
吗?userData
在QuestionView
中不存在。您是说practiceStatus
吗?PracticeView
内部呼叫PracticeView
!您肯定会得到堆栈溢出;-)您不是在说QuestionView
吗?以下是有效代码:
import Foundation
import SwiftUI
import Combine
class PracticeStatus: ObservableObject {
@Published var showResults:Bool = false
}
struct ContentView: View {
@State private var flag = false
var body: some View {
PracticeView().environmentObject(PracticeStatus())
}
}
struct PracticeView: View {
@EnvironmentObject var practiceStatus: PracticeStatus
var body: some View {
VStack {
if practiceStatus.showResults {
ResultView()
} else {
QuestionView()
}
}
}
}
struct QuestionView: View {
@EnvironmentObject var practiceStatus: PracticeStatus
var body: some View {
VStack {
Button(action: {
self.practiceStatus.showResults = true
}) {
Text("button")
}
}
}
}
struct ResultView: View {
@State private var flag = false
var body: some View {
Text("RESULTS")
}
}