当用户单击图像时,我想在 macOS 上打开一个下拉菜单。
我正在使用 Mac Catalyst 界面:针对 Mac 进行优化。
我之前可以使用 .buttonStyle(.plain)
这是代码:
Menu {
Button {
//action here
} label: {
Text("first button")
}
Button {
//action here
} label: {
Text("second button")
}
} label: {
Image(systemName: "arrow.up.arrow.down.circle")
.resizable()
.scaledToFit()
.foregroundColor(Color("SSGreen"))
.frame(width: scaleForMac(int: 34), height: scaleForMac(int: 34), alignment: .center)
}
.buttonStyle(.plain)
自从我升级到 Ventura 13.3.1 后,这似乎不再起作用。现在我得到一个微小的向下箭头,并且图像不渲染。
之前:
之后:
我做错了什么吗?如何继续获得能够让自定义 View 触发菜单的相同结果?
尝试创建自定义 buttonStyle
和自定义 menuStyle
但未能达到预期结果。
最佳答案
创建以下内容MenuStyle
:
struct DisplayLabelOnMacOSMenuStyle<Label: View>: MenuStyle {
let label: Label
func makeBody(configuration: Configuration) -> some View {
ZStack {
Menu(configuration)
.menuStyle(.borderlessButton)
label
.background(Color.white)
.allowsHitTesting(false)
.hidden(UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.userInterfaceIdiom == .phone)
}
}
}
并以这种方式使用它
Menu {
Button {
//action here
} label: {
Text("first button")
}
Button {
//action here
} label: {
Text("second button")
}
} label: {
menuLabel()
}
.menuStyle(
DisplayLabelOnMacOSMenuStyle(label: menuLabel())
)
// ...
@ViewBuilder
private func menuLabel() -> some View {
Image(systemName: "arrow.up.arrow.down.circle")
.resizable()
.scaledToFit()
.foregroundColor(Color("SSGreen"))
.frame(width: scaleForMac(int: 34), height: scaleForMac(int: 34), alignment: .center)
}
应该让您拥有与以前类似的外观和感觉,在 iPhone/iPad 上保持相同的行为,但要记住以下几点:
- 背景
Label
设置为白色,以免看到潜在透明的背后Label
,但您可能希望能够自定义背景颜色 - 单击菜单时,菜单元素存在轻微的填充问题
Label
,这是因为Menu
外观现在在 macOS 上是一个小箭头,与Label
的大小不同。 .
关于swift - 如何在 Ventura 13.3.1 中使用 SwiftUI 将图像设置为 MacCatalyst 上的菜单标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76074630/