所以我有一个 make 按钮函数,我在内容 View 的 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)
})
}
我在第一行收到一条错误语句:“函数声明了一个不透明的返回类型,但其主体中的返回语句没有匹配的基础类型。”我想这是因为一个可能的返回上的文本具有修饰符,而另一个则没有,或者它可能与操作代码块有关,但我不确定如何使该函数没有错误。我需要其中的保护语句,而且我也很想在函数末尾的按钮标签上放置修饰符。非常感谢任何帮助!
最佳答案
Swift/SwiftUI 对这些东西的语法很挑剔。
要返回不同类型并仍然符合某些 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")
})
}
}
关于swift - 如何从 SwiftUI 中带有修饰符的函数返回按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66936998/