SwiftUI How to pass data from child to parent as done in C# with the 'Delegate-EventHandler-EventArgs' way

Viewed 1442

I have already read this thread SwiftUI - Button - How to pass a function (with parameters) request to parent from child however after the original poster edited his own answer he proposed a way that didn't match his own question. Unfortunately I have not yet reached enough points to post comments in this thread

This is the code example from the post above repeated to explain the problem:

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

Here is possible solution. Tested with Xcode 11.4 / iOS 13.4

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

    @State private var value = "Child Value"
    var body: some View {
        Button(action: {
            self.function(self.value)
        }, label: {
            Text("Button")
        })
    }
}

struct ContentView: View {
    var body: some View {
        ChildView { self.setViewBackToNil(myStringParameter: $0) }
    }

    func setViewBackToNil(myStringParameter: String) {
        print("I am the parent: \(myStringParameter)")
    }
}
Related