I would like to conditionally display different views in my application - if a certain boolean is true, one view will be displayed. If it is false, a different view will be displayed. This boolean is within an ObservableObject class, and is changed from one of the views that will be displayed.
PracticeStatus.swift (the parent view)
import Foundation
import SwiftUI
import Combine
class PracticeStatus: ObservableObject {
@Published var showResults:Bool = false
}
PracticeView.swift (the parent view)
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
}) { ... }
...
}
}
}
However, this code doesn't work. When the button within QuestionView
is pressed, ResultView is not displayed. Does anybody have a solution? Thanks!
Have you tried to compile your code? There are several basic errors:
practice
does not exist inPracticeView
. Did you meanpracticeStatus
?userData
does not exist inQuestionView
. Did you meanpracticeStatus
?PracticeView
from insidePracticeView
! You'll definetely get a stack overflow ;-) Didn't you meanQuestionView
?Below is a working code: