首页 > 解决方案 > 如何在 SwiftUI 中以降低透明度为菜单项获取 AccentColor 背景?

问题描述

使用 AppKit,您可以将NSMenuItems 添加到NSMenu. 我看到 SwiftUI 中有一个类似于 NSMenu 的东西,即MenuButton. 但我找不到任何关于它如何工作的文档。

我尝试了以下方法:

MenuButton("+") {
    Button("New contact") { print("Create new contact") }
    Button("New group") { print("Create new group") }
}

这给了我这个

打开的 MenuButton

它看起来几乎可以,但是当我在系统偏好设置中启用“降低透明度”时

突出显示的菜单项

我还尝试使用.background()修饰符手动更改背景颜色,但这不会影响菜单项的整个宽度。

MenuButton("+") {
    Button("New contact") { print("Create new contact") }
        .background(Color.accentColor)
    Button("New group") { print("Create new group") }
}

具有手动更改背景的菜单

我想这是因为我将Buttons 放在其中,MenuButton而它可能期待其他一些 SwiftUI 元素。我应该在 MenuButtons 中放置哪些元素来创建如下所示的正常外观的 macOS 菜单?

在 Catalina 上正确渲染 MenuButton

[更新] macOS 大苏尔

我也在大苏尔试过这个。虽然背景渲染正确,但在 Big Sur 中,文本颜色现在混乱了。

Big Sur 上错误突出显示的菜单

标签: swiftmacosswiftui

解决方案


我想我通过配置 aButtonStyle并将其应用于MenuButton通用结构找到了部分解决方案。但是请注意,.foregroundColor个人的Button()'不会继承 的条件更改Text()。而且颜色也不对。

也许有人想改进这一点。

struct DetectHover: ButtonStyle {
    @State private var hovering: Bool = false

    public func makeBody(configuration: DetectHover.Configuration) -> some View {
        configuration.label
            .foregroundColor(self.hovering ? Color.white : Color.primary)
            .background(self.hovering ? Color.blue : Color.clear)
            .onHover { hover in
                self.hovering = hover
            }
    }
}
MenuButton(label: Image(nsImage: NSImage(named: NSImage.actionTemplateName)!)) {

// Buttons

}.buttonStyle(DetectHover())

结果


推荐阅读