How to return a Button from a function in SwiftUI?
If you look at the declaration of Button
, you can see that it is a generic struct
, so you need to supply its generic type parameter.
struct Button<Label> where Label : View
Make sure that you replace YourView
with the actual type implementing View
that you want to return.
class YourView: View { ... }
func buildButton(parameter : Parameter) -> Button<YourView> {
switch (parameter){
case Parameter.Value1:
return Button(
action: {
...
},
label: {
...
}
)
case Parameter.Value2:
return Button(
action: {...},
label: {
...
}
)
}
}
I'm not sure how important it is that you get a Button, but if you just need it to be displayed in another SwiftUI View without further refinements, you can just return some View
. You only have to embed all your Buttons in AnyView's.
func buildButton(parameter : Parameter) -> some View {
switch (parameter){
case Parameter.Value1:
return AnyView(Button(
action: {
...
},
label: {
...
})
)
case Parameter.Value2:
return AnyView(Button(
action: {...},
label: {
...
})
)
}
}