visc
visc

Reputation: 4959

How do you pass an action into a view and call it in the action of a button?

I have a ButtonView created and I can pass in the text and Color to style the Button when I init the View. But I would also like to pass a Button action into the initializer of the ButtonView and assign it to the action of the Button. How do I do this?

struct ButtonView: View {
var buttonText: String
var buttonColor: Color

var ACTION_DELEGATE_WANT_TO_DEFINE: Action

var body: some View {
        Button(action: 
             **ACTION I WAS TO PASS**
        ) {
            Text(buttonText)
                .foregroundColor(buttonColor)
        }
        .padding(EdgeInsets(top: 10, leading: 20, bottom: 10, trailing: 20))
        .overlay(
           RoundedRectangle(cornerRadius: 15)
            .stroke(buttonColor, lineWidth: 1)
        )
    }
}

I want to create the view like this:

ButtonView(buttonText: "Review App", buttonColor: .red, action: MyAction)

Upvotes: 0

Views: 82

Answers (1)

Chris
Chris

Reputation: 4391

The button action is simply a closure that accepts no arguments and returns nothing: () -> Void

You can set this as a parameter on your custom struct.

struct ButtonView: View {

    var buttonText: String
    var buttonColor: Color
    var actionClosure: () -> Void

    var ACTION_DELEGATE_WANT_TO_DEFINE: Action

    var body: some View {
        Button(action: 
             actionClosure()
        ) {
            Text(buttonText)
                .foregroundColor(buttonColor)
        }
        .padding(EdgeInsets(top: 10, leading: 20, bottom: 10, trailing: 20))
        .overlay(
           RoundedRectangle(cornerRadius: 15)
            .stroke(buttonColor, lineWidth: 1)
        )
    }
}

Upvotes: 1

Related Questions