How to return a Button from a function in SwiftUI?

ric*_*oma 8 button swift swiftui

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: {
                        ...
                }
            )
        }
    }
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

and the compiler gives

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

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

thi*_*oxe 17

我不确定获得 Button 有多重要,但是如果您只需要将它显示在另一个 SwiftUI 视图中而无需进一步改进,则只需返回some View. 您只需将所有按钮嵌入 AnyView 中。

func buildButton(parameter : Parameter) -> some View {
        switch (parameter){
            case Parameter.Value1:
                return AnyView(Button(
                    action: {
                        ...
                },
                    label: {
                        ...
                })
            )
            case Parameter.Value2:
                return AnyView(Button(
                    action: {...},
                    label: {
                        ...
                })
            )
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 这正是我一直在寻找的。来自 Flutter/React Native 背景,如果我只需要返回一个小部件/组件,我可以在函数声明中声明“some View”的返回类型,并将组件包装在“AnyView”中 (2认同)
  • 从 Xcode 12 开始,至少我发现我不需要在 AnyView 中嵌入 Button。没有它也可以正常工作,因此代码会更干净一些。 (2认同)