1

我将 @ObservedObject PropertyWrapper 用于我的 Picker 选择,并且我想在选择更改时在我的 View 结构中调用一个方法。我怎样才能做到这一点?

可观察对象代码:

class SphereModel: ObservableObject {
    @Published var selection = -3 {
        didSet {
            // Call method (getAD()) here
        }
    }
}

查看代码:

struct ContentView: View {
    
    @ObservedObject var sphereModel = SphereModel()

    var body: some View {
        Picker("Sphere Thickness", selection: $sphereModel.selection) {
            ForEach((-24..<1).reversed(), id: \.self) {
                Text(String(format: "%.1f", Double($0) / 2)).tag($0)
            }
        }
    }
    
    // Method to call
    func getAD() {
        
    }
}

我怎么做?谢谢!

4

1 回答 1

0

您可以onReceive直接在您的视图中使用:

class SphereModel: ObservableObject {
    @Published var selection = -3
}

struct ContentView: View {
    @ObservedObject var sphereModel = SphereModel()

    var body: some View {
        Picker("Sphere Thickness", selection: $sphereModel.selection) {
            ForEach((-24 ..< 1).reversed(), id: \.self) {
                Text(String(format: "%.1f", Double($0) / 2)).tag($0)
            }
        }
        .onReceive(sphereModel.$selection) { selection in
            print(selection)
            getAD()
        }
    }

    func getAD() {
        print("getAD")
    }
}
于 2020-10-13T23:23:47.427 回答