You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI:如何为工具栏中的Menu与工具栏本身设置不同配色方案

解决方案

当然可以实现,给你两种可行的方法:

方法一:单独设置导航标题颜色(推荐)

既然你只是想让导航标题在蓝色背景上显示清晰,没必要给整个导航栏设置dark配色,直接单独修改标题颜色就行,这样Menu会保持默认的light模式,不用额外调整。

修改后的代码:

NavigationView {
    List {
        Text("Row Title")
    }
    .toolbar {
        ToolbarItem(placement: .topBarTrailing) {
            Menu {
                Button {
                } label: {
                    Label("Report an Issue", systemImage: "exclamationmark.bubble")
                }
                Divider()
                Button(role: .destructive) {
                } label: {
                    Label("Delete", systemImage: "trash")
                }
            } label: {
                Label("Perform action", systemImage: "ellipsis.circle")
            }
        }
    }
    // 用带颜色的Text作为导航标题,替代toolbarColorScheme设置
    .navigationTitle(Text("My Documents").foregroundColor(.white))
    .toolbarBackground(Color.blue)
    .toolbarBackground(.visible)
}

这样导航标题是白色,和蓝色背景对比清晰,而Menu完全不受影响,保持light模式的样式。

方法二:自定义Menu样式(保留导航栏dark配色)

如果你一定要保留.toolbarColorScheme(.dark, for: .navigationBar)的设置,可以通过自定义MenuStyle强制Menu使用light模式的样式:

首先定义一个自定义样式:

struct LightMenuStyle: MenuStyle {
    func makeBody(configuration: Configuration) -> some View {
        Menu(configuration)
            .background(Color(UIColor.systemBackground)) // 用系统light模式背景色
            .foregroundColor(Color(UIColor.label)) // 系统light模式文本色
            .menuStyle(.borderlessButton)
    }
}

// 给MenuStyle加个扩展方便调用
extension MenuStyle where Self == LightMenuStyle {
    static var light: LightMenuStyle { .init() }
}

然后给你的Menu应用这个样式:

NavigationView {
    List {
        Text("Row Title")
    }
    .toolbar {
        ToolbarItem(placement: .topBarTrailing) {
            Menu {
                Button {
                } label: {
                    Label("Report an Issue", systemImage: "exclamationmark.bubble")
                        .foregroundColor(.black) // 手动设置按钮文本色
                }
                Divider()
                Button(role: .destructive) {
                } label: {
                    Label("Delete", systemImage: "trash")
                    // 销毁按钮的颜色会自动保持红色,不用额外修改
                }
            } label: {
                Label("Perform action", systemImage: "ellipsis.circle")
            }
            .menuStyle(.light) // 应用自定义light样式
        }
    }
    .navigationTitle("My Documents")
    .toolbarColorScheme(.dark, for: .navigationBar)
    .toolbarBackground(Color.blue)
    .toolbarBackground(.visible)
}

这个方法需要手动调整Menu内元素的颜色,确保和light模式一致,适合必须保留导航栏dark配色的场景。


内容的提问来源于stack exchange,提问作者Patrick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 13:03:15