首页 > 解决方案 > 切换 swiftUI toggle() 时如何触发操作?

问题描述

在我的 SwiftUI 视图中,当 Toggle() 更改其状态时,我必须触发一个动作。切换本身只需要一个绑定。因此,我尝试在 @State 变量的 didSet 中触发操作。但是 didSet 永远不会被调用。

是否有任何(其他)方式来触发动作?或者有什么方法可以观察@State 变量的值变化?

我的代码如下所示:

struct PWSDetailView : View {

    @ObjectBinding var station: PWS
    @State var isDisplayed: Bool = false {
        didSet {
            if isDisplayed != station.isDisplayed {
                PWSStore.shared.toggleIsDisplayed(station)
            }
        }
    }

    var body: some View {
            VStack {
                ZStack(alignment: .leading) {
                    Rectangle()
                        .frame(width: UIScreen.main.bounds.width, height: 50)
                        .foregroundColor(Color.lokalZeroBlue)
                    Text(station.displayName)
                        .font(.title)
                        .foregroundColor(Color.white)
                        .padding(.leading)
                }

                MapView(latitude: station.latitude, longitude: station.longitude, span: 0.05)
                    .frame(height: UIScreen.main.bounds.height / 3)
                    .padding(.top, -8)

                Form {
                    Toggle(isOn: $isDisplayed)
                    { Text("Wetterstation anzeigen") }
                }

                Spacer()
            }.colorScheme(.dark)
    }
}

期望的行为是当 Toggle() 更改其状态时触发操作“PWSStore.shared.toggleIsDisplayed(station)”。

标签: swifttoggleswiftui

解决方案


SwiftUI 2

如果您使用的是SwiftUI 2 / iOS 14,您可以使用onChange

struct ContentView: View {
    @State private var isDisplayed = false
    
    var body: some View {
        Toggle("", isOn: $isDisplayed)
            .onChange(of: isDisplayed) { value in
                // action...
                print(value)
            }
    }
}

推荐阅读