Reputation: 91
Suppose I have some environmental object that stores the states of a user being signed in or not;
class Account: ObservableObject{
@Published var isSignedIn: Bool = false
}
I want to conditional display a view if the user is signed in. So, app loads -> RootView(). If user is signed In -> go to Profile, otherwise go to LoginScreen
struct RootView: View {
@EnvironmentObject private var account: Account
var body: some View {
NavigationStackViews{
// This is just a custom class to help display certain views with a transition animation
if account.isSignedIn{ // I only want to read this ONCE. Otherwise, when this value changes, my view will abruptly change views
ProfileView()
} else { SignInView() }
}
}
}
Upvotes: 0
Views: 331
Reputation: 30341
Set a @State
variable in onAppear(perform:)
of the current isSignedIn
value. Then use that in the view body instead.
Code:
struct RootView: View {
@EnvironmentObject private var account: Account
@State private var isSignedIn: Bool?
var body: some View {
NavigationStackViews {
if let isSignedIn = isSignedIn {
if isSignedIn {
ProfileView()
} else {
SignInView()
}
}
}
.onAppear {
isSignedIn = account.isSignedIn
}
}
}
Upvotes: 1