macos - SwiftUI (2.) for MacOS 中的 Buggy 菜单控件
问题描述
这是针对 MacOS 的。我正在尝试使用新的菜单控件在 SwiftUI 中重新创建下拉菜单按钮。菜单有几个由分隔线分隔的部分。每个部分应该只能在一个项目上设置一个刻度线。我最初有一个自定义的 ButtonGroup 视图来处理这些部分,但它不起作用,所以我将它简化为下面的代码,但它仍然不能正常工作。我希望得到一个带有 A、B 的菜单,然后是一个分隔符,然后是 C、D、E、F 但我得到 A、B | A,B,E,F 代替。在一个组中选择一个项目也会在另一个组中创建一个刻度,并且菜单也会发生变化。选择一个项目后,我有时会得到 CD | CDEF。在我提交错误报告之前,谁能看到出了什么问题?
struct ContentView: View {
@State private var selected1: Int = -1
@State private var selected2: Int = 2
var items1 = ["A", "B"]
var items2 = ["C", "D","E", "F"]
var body: some View {
ZStack{
Menu("Configure") {
ForEach(0..<items1.count){ index in
Button((index == selected1 ? "✔︎ " : " ") + items1[index], action: {
selected1 = index
})
}
Divider()
ForEach(0..<items2.count){ index in
Button((index == selected2 ? "✔︎ " : " ") + items2[index], action: {
selected2 = index
})
}
}.frame(width: 70)
}.frame(width: 200, height: 200)
}
}
解决方案
混淆了 same id
,因为在两个动态组中您都使用索引,所以第一个中的 0, 1 和第二个中的 0, 1 是重叠的。
最好的方法是为每个创建显式菜单项模型和唯一标识符,但对于您的演示案例,也可以使用以下方法
Menu("Configure") {
ForEach(Array(items1.enumerated()), id: \.1){ index, item in
Button((index == selected1 ? "✔︎ " : " ") + item, action: {
selected1 = index
})
}
Divider()
ForEach(Array(items2.enumerated()), id: \.1){ index, item in
Button((index == selected2 ? "✔︎ " : " ") + item, action: {
selected2 = index
})
}
}.frame(width: 70)
推荐阅读
- tensorflow - 加快 GPT2 的推理时间 - 优化 tf.sess.run()
- mysql - 我如何在sql中编写条件以获得所需的结果SQL
- python - 新行,在控制台中打印有问题
- charts - PHP电子表格图表设置轴范围
- javascript - Javascript多维数组更新一个值但全部更新
- mysql - AWS RDS automatically stopping soon after it is started
- c - 我可以同时对同一个 kobj 上的多个属性使用 sysfs_notify() 吗?
- javascript - 如何获取 $ (this) .children 内部元素属性的值?
- mysql - Zsh 说我的 shell 脚本中有一个无与伦比的 ' 。它在哪里?
- php - 如何在php中使html表格行相等