如何在 macOS 中将 SwiftUI 菜单项与复选标记对齐?

spt*_*025 4 macos xcode swift swiftui

我正在尝试在 MacOS 应用程序中使用 swiftUI 制作菜单。

基于此:

代码参考链接

另一个参考链接

我正在使用这个特定的代码

struct SelectionRow: View {
    var title: String
    var isSelected: Bool
    var action: () -> Void

    var body: some View {
        Button(action: self.action) {
            HStack {
                if self.isSelected {
                    Image("checkmark")
                        .resizable()
                        .renderingMode(.template)
                        .scaledToFit()
                } else {
                    //FIXME: What to add here ???!!! <-- Need to add solution here I believe
                }
                Text(self.title)
                    //.frame(alignment: .trailing). <-- Not effective
            }
        }.foregroundColor(Color.black)
    }
}
Run Code Online (Sandbox Code Playgroud)

菜单项条目:

Menu("Example Menu"){
    SelectionRow(title: "One", isSelected: true, action: { print("hello world")})
    SelectionRow(title: "Two", isSelected: false, action: { print("hello world")})
    SelectionRow(title: "Three", isSelected: true, action: { print("hello world")})
}
Run Code Online (Sandbox Code Playgroud)

菜单图片

如果您查看图像,“二”菜单项与“一”和“三”菜单选项不对齐,因为选项“一”和“三”有一个复选标记的图像。我尝试使用最小宽度的间隔器(以及其他一些选项),但似乎不起作用并将“二”与“一”和“三”对齐

您能推荐任何可以解决此问题并使“二”与“一”和“三”对齐的方法吗?

hus*_*gle 10

这并不能完全回答您提出的问题,而是达到了我认为您的目标。尝试使用切换按钮代替按钮,如下所示:

Menu("Example Menu") {
    let oneBinding = Binding<Bool>(
        get: { return true },
        set: { _,_ in } )
    Toggle(isOn: oneBinding) {
        Text("One")
    }

    Button {
        print("Two as a Button")
    } label: {
        Text("Two as a Button")
    }

    let twoBinding = Binding<Bool>(
        get: { return false },
        set: { _,_ in } )
    Toggle(isOn: twoBinding) {
        Text("Two as a Toggle")
    }

    let threeBinding = Binding<Bool>(
        get: { return true },
        set: { _,_ in } )
    Toggle(isOn: threeBinding) {
        Text("Three")
    }
}
Run Code Online (Sandbox Code Playgroud)

它在 macOS 上的外观如下:

包含四个项目的菜单,其中两个带有复选标记。 标题全部与前导槽中的复选标记对齐。

这是 iOS 系统:

iOS 上的菜单相同。 标题仍然对齐,复选标记位于前导槽中。

项目标题全部对齐,无论是切换按钮还是按钮,并且复选标记沿引导方向延伸菜单。这不允许您在菜单项中使用任意图像,但它适用于指示切换菜单项的复选标记的特定情况。

像这样及时创建绑定并不是很好的编码风格,但是对于这样的代码片段来说它是有用的,并且可以清楚地表明发生了什么。对于这些,我已经硬编码了条件,但是您可以在绑定 get 和 set 方法中任意喜欢。

我有一些这样的代码,让我可以在表示从远程服务器提取的数据的核心数据对象中切换一些布尔值。在我的绑定的 get 方法中,我返回已传递到我的视图的对象的属性值。在绑定的 set 方法中,我做了一些 NSManagedObjectContext jig 来创建对象的私有副本,其中我将正在使用的属性设置为不是其本身,然后将私有对象传递给另一个对象中的方法,该方法写入数据发送到远程服务器并刷新持久存储中的真实副本。