SwiftUI:有什么方法可以将自定义按钮样式添加到 Menu() 中吗?

Mal*_*ito 18 menu button styling swift swiftui

我已经尝试了很长一段时间向 SwiftUI Menu() 的标签添加自定义按钮样式/行为,但到目前为止还没有取得任何成功。这是我想要实现的目标的示例:

自定义按钮样式

假设我有一个自定义按钮样式,可以让按钮的文本在按下时变为红色。

struct RedButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .foregroundColor(configuration.isPressed ? .red : .primary)
}
Run Code Online (Sandbox Code Playgroud)

菜单

另外,我有一个标准的 SwiftUI 菜单。

Menu("Menu button", content: {
    // Some menu content goes here
})
Run Code Online (Sandbox Code Playgroud)

在此配置中,SwiftUI 菜单以强调色(系统蓝色)显示一个标准按钮,其行为类似于标准按钮(按下时变灰)。按下后,菜单将按预期显示。

自定义菜单按钮

现在我想以某种方式将自定义按钮样式应用到菜单正在使用的按钮。我尝试的是以下内容:

Menu(content: {
    // Some menu content goes here
}, label: {
    Button("Menu button", action: { })
        .buttonStyle(RedButtonStyle())
})
Run Code Online (Sandbox Code Playgroud)

然而,菜单按钮的行为根本没有改变——按下时它仍然只是变灰,而不是变成红色。

我还尝试了创建自定义菜单样式,但到目前为止还没有取得任何成功。

对此有何建议?谢谢!

ARG*_*Geo 2

菜单标签颜色

在 iOS 15.0+ 中,有一个init(_:role:action:)初始化程序允许您使用.destructive角色创建红色标签颜色。如果您不打算删除用户数据,请为您的按钮使用此角色。代码如下所示:

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        ZStack {
            Color.black.ignoresSafeArea()
            
            Menu("Actions") {
                Button(role: .destructive, action: { }) {
                    Label("Apple Swift 6.0", systemImage: "swift")
                        .font(.largeTitle)
                }
            }
            .font(.largeTitle)
            .foregroundColor(.yellow)              
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

菜单按钮颜色

这是我更改菜单按钮文本颜色的解决方法。

import SwiftUI

struct ContentView: View {
    
    @State private var color: Color = .red
    
    var body: some View {
        
        let press = LongPressGesture(minimumDuration: 0.0001)
                                         .onChanged { _ in color = .yellow }
                                         .onEnded { _ in color = .red }

        ZStack {
            Color.black.ignoresSafeArea()
            
            Menu("Choose") {
                Button(role: .none, action: { }) {
                    Label("Apple Swift 6.0", systemImage: "swift")
                }
            }
            .font(.largeTitle)
            .foregroundColor(color)
            .gesture(press)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

聚苯乙烯

在 iOS 15.5 和 macOS 12.4 上测试。