How to call a method in my View struct from my ObservableObject class

189 views Asked by At

I am using the @ObservedObject PropertyWrapper for my Picker selection and I want to call a method in my View struct when the selection changes. How can I do that?

ObservableObject Code:

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

View Code:

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

How do I do that? Thanks!

1

There are 1 answers

1
pawello2222 On

You can use onReceive directly in your view:

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