Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

swiftui

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)

like image 468
Vladyslav Lopatin Avatar asked Dec 18 '25 09:12

Vladyslav Lopatin


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.

like image 74
Vladyslav Lopatin Avatar answered Dec 21 '25 14:12

Vladyslav Lopatin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!