SwiftUI - Button - How to pass a function (with parameters) request to parent from child

Viewed 2280

I already know how to call a parent function from child but what I should do if my parent function has a parameter? I can't figure it out...

Working code without parameters:

struct ChildView: View {
    var function: () -> Void

    var body: some View {
        Button(action: {
            self.function()
        }, label: {
            Text("Button")
        })
    }
}

struct ContentView: View {
    var body: some View {
        ChildView(function: { self.setViewBackToNil() })
    }

    func setViewBackToNil() {
        print("I am the parent")
    }
}

And now I want to add a String parameter to setViewBackToNil(myStringParameter: String)

1 Answers

Ok, I managed to solve it.

You can use @State variable in a parent, and pass it to your child. Then, after changing it in the child view, call function, that was passed from the parent (without parameters), and in the parent get your @State inside the function.

Related