如何通过 Toggle Swiftui 传递函数

How Can I Pass Function Through A Toggle Swiftui

状态变量:

@State var toggleIsOn = false

切换:

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

我想要以下按钮,代表开关的每个状态,打开和关闭:

                // 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()
                }

我在这个视频中找到了函数:https://www.youtube.com/watch?v=mG9BVAs8AIo

使用

onChange(of:)

例如:

    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()
             }
        }
    }
}