Trigger an action when toggle

hejliang

Liang Wang

Posted on February 11, 2024

Trigger an action when toggle

I have a toggle in my app Settings where I can switch on and off the onboarding view.

Previously I was using if/else at App start to check if show onboarding, but now I have app state as Environment Object, I need to be able to change app state with something like:

if isOnboarding {
                    appManager.restartOnboarding()
                  }
Enter fullscreen mode Exit fullscreen mode

So I found this link: and the example code like below

struct ContentView: View {
    @State private var isDisplayed = false

    var body: some View {
        Toggle("", isOn: $isDisplayed)
            .onChange(of: isDisplayed) {
                print("Action")
            }
            .onChange(of: isDisplayed) { oldValue, newValue in
                // action...
                print(oldValue, newValue)
            }
    }
}
Enter fullscreen mode Exit fullscreen mode

This works for me.

💖 💪 🙅 🚩
hejliang
Liang Wang

Posted on February 11, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related