I am new to SwiftUI and want to display a view based on a boolean value but every time I run my app in the simulator, it always runs the else
part and displays ContentView
instead of OnboardingView
.
Kindly guide what I am doing wrong in the code.
import SwiftUI
@main
struct FirstApp: App {
@AppStorage("isOnboarding") var isOnboarding: Bool = true
var body: some Scene {
WindowGroup {
if isOnboarding {
OnboardingView()
} else
{
ContentView()
}
}
}
}
CodePudding user response:
The code works fine. The "problem" is the persisted value in your device for key "isOnboarding"
is false (the default value that you have assigned will work only the first them). To make sure that this statement is right, you can do a simple test: toggle the isOnboarding
value and relaunch the app. Something like this:
@main
struct FirstApp: App {
@AppStorage("isOnboarding") var isOnboarding: Bool = true
var body: some Scene {
WindowGroup {
Toggle(isOn: $isOnboarding) {
Text("isOnboarding")
}
if isOnboarding {
OnboardingView()
} else {
ContentView()
}
}
}
}