Reputation: 4959
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
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