DEV Community

Liang Wang
Liang Wang

Posted on

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.

Top comments (0)