如何从SwiftUI中的函数返回Button? [英] How to return a Button from a function in SwiftUI?

查看:61
本文介绍了如何从SwiftUI中的函数返回Button?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据一些参数动态创建一个按钮

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:

对泛型类型'Button'的引用需要< ...>中的参数.插入'<< #Label:View#>>'

Reference to generic type 'Button' requires arguments in <...>. Insert '<<#Label: View#>>'

因此,如果单击 Fix ,函数声明将变为

So if I click Fix, the function declaration becomes

func buildButton(parameter : Parameter) -> Button<Label:View>

编译器给出

使用未声明的类型'< #Label:View#>'

Use of undeclared type '<#Label: View#>'

我需要在此处插入什么才能返回 Button ?

What do I need to insert here to be able to return a Button?

推荐答案

我不确定获得一个Button有多重要,但是如果您只需要将其显示在另一个SwiftUI视图中而无需进一步完善,您会发现可以只返回一些视图.您只需要将所有按钮嵌入到AnyView中即可.

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: {
                        ...
                })
            )
        }
    }

这篇关于如何从SwiftUI中的函数返回Button?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆