SwiftUI:轻按切换按钮并更改变量状态时调用函数

时间:2020-08-06 15:45:42

标签: function binding swiftui state toggle

我知道已经有一个关于该主题(How can I trigger an action when a swiftUI toggle() is toggled?)的主题,但是我尝试了所有答案,但没有任何效果。

首先输入我的代码

struct ContentView: View {
    
    @State private var isOn = false
    
    
    var body: some View {
        
        NavigationView{
            VStack{
                ZStack {
                    Form{
                        // HERE THE IMPORTANT PART

                        Toggle(isOn: %isOn) {
                            Text(isOn ? "On" : "Off")
                            
                            /*if(isOn){
                                Text("\(sendState(state: isOn))")
                            }else{
                                Text("\(sendState(state: isOn))")
                            }*/
                              //--> that is a workaround but doesn't work for me because the function send something to the server and that should only happen when the Toggle State is changed but now the function is called every time the view is changed//


                        }
                    }
                }
            }
            
    func sendState(state: Bool){
        if state{
            mqttClient.publish("rpi/gpio", withString: "on")
            print("Published ON")
        }else{
            mqttClient.publish("rpi/gpio", withString: "off")
            print("Published OFF")
        }
    }
}

因此,我想做的是当我点击切换开关并且isOn的状态变为true或false时调用函数sendState(state:isOn)。我尝试了willSet,didSet,自己的绑定扩展和其他一些东西,但是没有什么能像我上面所说的那样工作。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

SwiftUI 2.0

Xcode 12 / iOS 14

简单

Toggle(isOn: $isOn) {
    Text(isOn ? "On" : "Off")
}.onChange(of: isOn) {
    self.sendState(state: $0)
}

SwiftUI 1.0 + (仍然有效)

有点复杂

Toggle(isOn: $isOn) {
    Text(isOn ? "On" : "Off")
}.onReceive([isOn].publisher.first()) {
    self.sendState(state: $0)
}