5

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 Answer 1

3

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")
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.