swift - 如何在 Ventura 13.3.1 中使用 SwiftUI 将图像设置为 MacCatalyst 上的菜单标签

标签 swift swiftui menu mac-catalyst macos-ventura

当用户单击图像时,我想在 ma​​cOS 上打开一个下拉菜单。

我正在使用 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 后,这似乎不再起作用。现在我得到一个微小的向下箭头,并且图像不渲染。

之前:

Before

之后:

After

我做错了什么吗?如何继续获得能够让自定义 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 的大小不同。 .

padding issue

关于swift - 如何在 Ventura 13.3.1 中使用 SwiftUI 将图像设置为 MacCatalyst 上的菜单标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76074630/

相关文章:

ios - 'NSInternalInconsistencyException',原因 : 'attempt to insert row 4 into section 0, but there are only 4 rows in section 0 after the update'

ios - Swift 中 private 关键字的使用及其在协议(protocol)中的使用?

ios - 带有很多按钮的 VStack 上的 DragGesture,如何检测拖动何时在按钮内

css - 下拉菜单在 Safari 浏览器中不起作用

php - Joomla 3 - 菜单搜索引擎友好的 URL

javascript - 固定 div 右侧的悬停菜单

iOS拖动UIView,布效果

ios - 关于所选按钮的奇怪外观

swift - 为什么选择器绑定(bind)在使用 SwiftUI 时不更新?

ios - 如何在 swiftui 中添加填充而不是边距