首页 > 解决方案 > 如何从 SwiftUI 中的带有修饰符的函数返回按钮?

问题描述

所以我有一个制作按钮功能,我在我的内容视图中的 ForEach 循环中调用它......这里是:

func makeButton(info: Info) -> some View {
    guard let variable = value else { return
        Button(action: {
            print("printing now...")
        }, label: {
            Text("Label")
        })
    }
    return Button(action: {
        //execute a function here
    }, label: {
        Text("Other Label")
            .padding(.vertical, 20)
            .frame(width: UIScreen.main.bounds.width * 0.8)
            .background(Color.white)

    })
}

我在第一行收到一条错误语句:“函数声明了一个不透明的返回类型,但其主体中的返回语句没有匹配的基础类型。” 我猜这是因为一个可能返回的 Text 有修饰符而另一个没有,或者它可能与操作代码块有关,但我不确定如何使这个函数无错误。我需要其中的保护语句,并且我也很想在函数末尾的按钮标签上添加修饰符。非常感谢任何帮助!

标签: swiftxcodebuttonviewswiftui

解决方案


Swift/SwiftUI 对这些东西的语法很挑剔。

要返回不同的类型并仍然符合some View,您必须使用@ViewBuilder. using@ViewBuilder也意味着您使用隐式返回,因此结构会略有不同(否guard let):

@ViewBuilder func makeButton() -> some View {
        if let variable = value {
            Button(action: {
                //execute a function here
            }, label: {
                Text("Other Label")
                    .padding(.vertical, 20)
                    .frame(width: UIScreen.main.bounds.width * 0.8)
                    .background(Color.white)

            })
        } else {
            Button(action: {
                print("printing now...")
            }, label: {
                Text("Label")
            })
        }
    }

推荐阅读