swift - 如何从 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 有修饰符而另一个没有,或者它可能与操作代码块有关,但我不确定如何使这个函数无错误。我需要其中的保护语句,并且我也很想在函数末尾的按钮标签上添加修饰符。非常感谢任何帮助!
解决方案
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")
})
}
}
推荐阅读
- kframework - 如何在 kframework 的一个规则中“要求”两件事?
- excel - 有没有办法克服 VBA 中随意的编辑导航?
- matlab - 以指定概率随机选择两个选项之一
- php - 使用 PHP 在 mysql 数据库上加载文本文件
- sql - 限制关系数据库中的用户可以编辑哪些行
- elasticsearch - 是否有用于索引/搜索序数作为数值的过滤器?
- ios - WKWebview 允许LinkPreview 假断文本选择
- jquery - 如何从选项中选择字体真棒图标
- laravel - 使用 Route 对象从控制器方法内部获取路由参数是否被认为是一种不好的做法?[拉拉维尔]
- python - 如何在多对多关系中获得总数?