Search code examples
functionswiftuinotificationsswitch-statementtoggle

How Can I Pass Function Through A Toggle Swiftui


State var:

@State var toggleIsOn = false

Toggle:

Toggle(isOn: $toggleIsOn, label: {Text("Notifications")})

I want the following buttons, to represent each state of the toggle, on and off:

                // Will request to send notifications, if success; will schedule them.
                Button("request") {
                    NotificationManager.instance.requestAuthorization()
                }
                // Will clear the queue of notifications, and delete any delivered.
                Button("cancel") {
                    NotificationManager.instance.cancelNotifications()
                }

I found the functions in this video: https://www.youtube.com/watch?v=mG9BVAs8AIo


Solution

  • use

    onChange(of:)

    for example:

        struct ContentView: View {
        @State var toggleIsOn: Bool = false
    
        var body: some View {
            Toggle(isOn: $toggleIsOn, label: {Text("Notifications")})
            .onChange(of: toggleIsOn) { isOn in
                 if isOn {
                      NotificationManager.instance.requestAuthorization()
                 } else {
                      NotificationManager.instance.cancelNotifications()
                 }
            }
        }
    }