问题
I need to dynamically create a Button based on some parameters
func buildButton(parameter : Parameter) -> Button {
switch (parameter){
case Parameter.Value1:
return Button(
action: {
...
},
label: {
...
}
)
case Parameter.Value2:
return Button(
action: {...},
label: {
...
}
)
}
}
But the compiler gives me this error:
Reference to generic type 'Button' requires arguments in <...>. Insert '<<#Label: View#>>'
So if I click Fix, the function declaration becomes
func buildButton(parameter : Parameter) -> Button<Label:View>
and the compiler gives
Use of undeclared type '<#Label: View#>'
What do I need to insert here to be able to return a Button?
回答1:
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: {
...
})
)
}
}
回答2:
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: {
...
}
)
}
}
来源:https://stackoverflow.com/questions/57322631/how-to-return-a-button-from-a-function-in-swiftui