swiftui - SwiftUI:如何只为 iPhone 显示一些工具栏按钮
问题描述
我有一组工具栏按钮,只有当设备是 iPhone(不是 iPad)时才应该显示。
以下代码因此错误而失败:
包含控制流语句的闭包不能与结果生成器“ToolbarContentBuilder”一起使用
我确实理解它为什么会失败,但我无法想出一个解决方案来满足我的需要。
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
List {
NavigationLink(
destination: Hello(),
label: {
Text("Hello")
})
}
}
}
}
struct Hello: View {
var body: some View {
Text("Hello World")
.toolbar() {
if UIDevice.current.userInterfaceIdiom == .phone {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
// do something
}, label: {
Text("Button1")
})
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
// do something
}, label: {
Text("Button2")
})
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
// do something
}, label: {
Text("Button3")
})
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
我很高兴创建一个单独的函数来实现它。我根本不知道该怎么做。
解决方案
可能你想要这个
struct Hello: View {
var body: some View {
Text("Hello World")
.toolbar() {
ToolbarItemGroup(placement: .navigationBarTrailing) {
if UIDevice.current.userInterfaceIdiom == .phone {
Button(action: {
// do something
}, label: {
Text("Button1")
})
Button(action: {
// do something
}, label: {
Text("Button2")
})
}
Button(action: {
// do something
}, label: {
Text("Button3")
})
}
}
}
}
推荐阅读
- c++ - 在 C++ 中实现地图矢量
- angular7 - 存储哪个树节点是展开 mat-tree 嵌套的?
- excel - 如何计算范围参数中的项目数?
- excel - 从Excel中一系列单元格中以逗号分隔的一组数字中计算特定数字
- python - 如何统一使用 TensorFlow python 项目,然后可以构建到 iOS
- genetic-algorithm - 使用遗传算法分配客人
- javascript - 如何测试用 jest 和 redux saga 调用 api 的函数
- jquery - 如何使用 jQuery 插入元素?
- postgresql - Postgres查询不使用索引
- bash - DNS解析器脚本