适用于MacOS的SwiftUI(2.)中的Buggy菜单控件 [英] Buggy Menu Control in SwiftUI (2.) for MacOS

查看:91
本文介绍了适用于MacOS的SwiftUI(2.)中的Buggy菜单控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是针对MacOS的.我正在尝试使用新的Menu控件在SwiftUI中重新创建下拉菜单按钮.菜单有几个部分,中间用分隔符分隔.每个部分只能在一个项目上设置刻度线.我最初有一个自定义的ButtonGroup视图来处理这些部分,但是它不起作用,因此我将其简化为下面的代码,但仍然无法正常工作.我希望得到一个菜单,其中A,B然后是分隔线,然后是C,D,E,F,但我得到A,B |取而代之的是A,B,E,F.在一个组中选择一个项目也会在另一个组中创建一个勾号,并且菜单也会更改.选择项目后,有时我会得到CD |CDEF.在提交错误报告之前,谁能看到问题出在哪里?

This is for MacOS. I am trying to recreate a pull down menu button in SwiftUI using the new Menu control. The menu has several sections separated by a Divider. Each section should be able to set a tick mark on one item only. I originally had a custom ButtonGroup view to handle the sections but it didn't work, so I simplified it to the code below, but it still doesn't work properly. I would expect to get a menu with A,B then a divider, then C,D,E,F but I get A,B | A,B,E,F instead. Selecting an item in one group also create a tick in the other group and the menus change as well. After selecting an item I sometimes get CD | CDEF. Can anyone see what is going wrong before I submit a bug report?

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)
    }
}

推荐答案

它被相同的 id 混淆,因为在两个动态组中您都使用索引,因此0、1开头和0、1在第二秒是重叠的.

It is confused by same id, because in both dynamic groups you use indexes, so 0, 1 in first and 0, 1 in second are overlapped.

最好是为每个菜单项创建显式菜单项模型和唯一标识符,但是对于您的演示案例,也可以使用以下方法

The best would be to create explicit menu item model and unique identifier for each, but for your demo case it is possible to use also the following approach

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)

这篇关于适用于MacOS的SwiftUI(2.)中的Buggy菜单控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆