How to return a Button from a function in SwiftUI?

喜你入骨 提交于 2021-01-21 04:42:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!