我写了类似下面的代码。创建菜单信息 (MenuInfo) 结构并在 MenuInfo 数组中创建一些菜单项。我现在正在尝试遍历这些来创建菜单。 (现在只是打印数组中的详细信息)。下面的代码用于展示概念,可能无法编译。我收到以下错误:
静态方法“buildExpression”要求“ToolbarItemGroup
不确定我做错了什么,但当我注释掉整个 ToolbarItemGroup -> for 部分时,问题就消失了。该错误打印在第一个 ToolbarItemGroup 旁边,这当然是正确的,并且错误并不具体。
enum Tools {
case a, b
}
struct MenuInfo {
var name: String
var image: String
var tool: Tools
init(_ name: String,_ image: String,_ tool: Tools ) {
self.name = name
self.image = image
self.tool = tool
}
}
private var qMark = "questionmark"
// Name Image Tool
var myMenu = [
MenuInfo( "A", qMark, .a ),
MenuInfo( "B", qMark, .b )
]
struct ContentView: View {
@State private var curToolSet = ToolSet.eng
@State private var curTool = Tools.arrow
var body: some View {
VStack {
Text( "Content" )
.toolbar {
ToolbarItemGroup {
Menu(content: {
Button( "Hi" ) { curToolSet = .eng }
}, label:{ Text( "Engineering" )})
}
// ToolbarItemGroup {
// for curMenu in myMenu {
// Button( curMenu.name, systemImage: curMenu.image ) {
// }
// }
// }
} // End toolbar
} // End vStack
.frame( height: 500 )
.frame( width: 800 )
} // End View
private func selectTool() {
print(" in selectTool ")
}
}
#Preview {
ContentView()
}
不要使用
for
循环,而是使用 ForEach
:
ForEach(myMenu, id: \.name) { (curMenu) in
Button(curMenu.name, systemImage: curMenu.image)
}
如果传递给
ForEach
的数组中的项目符合 Identifiable
,则可以跳过 id:
参数。如果没有,您必须传入 ForEach
可以用作唯一标识符的属性名称。 (我只是猜测 name
字段就是您想要的。)