pass button action from parent to child swiftui in swift

In SwiftUI, you can pass the button action from parent to child using a closure. Here's an example:

main.swift
// Parent View
struct ParentView: View {
    var body: some View {
        ChildView(action: buttonAction)
    }
    
    func buttonAction() {
        print("Button pressed")
    }
}

// Child View
struct ChildView: View {
    var action: (() -> Void)

    var body: some View {
        Button("Press me") {
            self.action()
        }
    }
}
353 chars
22 lines

In the parent view, we create an instance of the child view and pass the buttonAction function to it using the action parameter.

Then, in the child view, we define a closure type with no parameters and no return value, which is stored in the action parameter. When the button is pressed, the closure is called, which in turn calls the buttonAction function in the parent view.

This pattern can be used to pass any kind of function from parent to child in SwiftUI.

related categories

gistlibby LogSnag