Call parent view's function from child view with parameters

Viewed 503

I'd like to call parent View's function from Child View with parameters.
Following code is error.

struct ContentView: View {
    func update(value: Double) {
        print("called update: \(value)")
    }

    var body: some View {
        ChildView(onUpdate: update)
    }
}

struct ChildView: View {
    var onUpdate: (value: Double) -> ()

    var body: some View {
        VStack {
            Text("child view")
            Button(action: {
                self.onUpdate(value: 3.0)
            }) {
                Text("onUpdate")
            }
        }
    }
}
1 Answers

Here is fixed variant. Tested with Xcode 11.4 / iOS 13.4

struct ChildView: View {
    var onUpdate: (Double) -> ()   // << no labels, just types !!

    var body: some View {
        VStack {
            Text("child view")
            Button(action: {
                self.onUpdate(3.0)
            }) {
                Text("onUpdate")
            }
        }
    }
}
Related