swift - 如何在 SwiftUI 中以降低透明度为菜单项获取 AccentColor 背景?
问题描述
使用 AppKit,您可以将NSMenuItem
s 添加到NSMenu
. 我看到 SwiftUI 中有一个类似于 NSMenu 的东西,即MenuButton
. 但我找不到任何关于它如何工作的文档。
我尝试了以下方法:
MenuButton("+") {
Button("New contact") { print("Create new contact") }
Button("New group") { print("Create new group") }
}
这给了我这个
它看起来几乎可以,但是当我在系统偏好设置中启用“降低透明度”时
- 按钮的背景颜色与菜单不同(请注意菜单项上方和下方的颜色稍浅)。
- 当我悬停菜单项时,它们的背景颜色不会像普通的 macOS 菜单那样改变。见下图:
我还尝试使用.background()
修饰符手动更改背景颜色,但这不会影响菜单项的整个宽度。
MenuButton("+") {
Button("New contact") { print("Create new contact") }
.background(Color.accentColor)
Button("New group") { print("Create new group") }
}
我想这是因为我将Button
s 放在其中,MenuButton
而它可能期待其他一些 SwiftUI 元素。我应该在 MenuButtons 中放置哪些元素来创建如下所示的正常外观的 macOS 菜单?
[更新] macOS 大苏尔
我也在大苏尔试过这个。虽然背景渲染正确,但在 Big Sur 中,文本颜色现在混乱了。
解决方案
我想我通过配置 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())
推荐阅读
- android - android-无法启动守护进程
- python - 提取字符串中特定列下的值
- solidity - 如何在 REMIX(Solidity IDE)中从 web3 调用带有参数的构造函数
- java - Firebase Recycler View Adapter(从 firebase 检索)
- javascript - 如何运行用 typescript 为节点编写的 jasmine 测试
- django - Django/RestFramework:如何从具有外键的模型中获取数据
- laravel - Laravel 读取文件内容并保持格式
- vba - 检测到错误 500 时刷新 Internet Explorer
- google-sheets - 谷歌表 - sumif 值与文本
- ruby-on-rails-5 - ruby on rails 5.2 --“form for”无法更新