问题描述
我有一组工具栏按钮,只有在设备是 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")
})
}
}
}
}