【问题标题】:How to return a button from a function WITH modifiers in SwiftUI?如何在 SwiftUI 中从带有修饰符的函数返回按钮?
【发布时间】:2021-06-30 08:51:38
【问题描述】:

所以我有一个制作按钮功能,我在内容视图的 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 有修饰符而另一个没有,或者它可能与操作代码块有关,但我不确定如何使这个函数无错误。我需要其中的保护语句,并且我还真的很想在函数末尾的按钮标签上放置修饰符。非常感谢任何帮助!

【问题讨论】:

    标签: swift xcode button view swiftui


    【解决方案1】:

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

    要返回不同的类型并仍然符合some View,您必须使用@ViewBuilder。使用@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")
                })
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      相关资源
      最近更新 更多