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

深色模式下BorderedProminent按钮文字消失,求自适应样式方案

解决SwiftUI .borderedProminent按钮明暗模式文字适配问题

你遇到的问题是因为 .tint(.primary) 与系统默认的 .borderedProminent 配色逻辑冲突:浅色模式下primary为黑色,系统自动把文字设为白色,显示正常;但深色模式下primary为白色,文字仍沿用系统默认的白色,导致文字与背景重叠不可见。而禁用状态正常是因为系统会自动替换禁用态的配色方案。

下面是一种简洁的解决方案,通过自定义ButtonStyle实现自适应配色,同时保留primary的禁用态样式:

struct AdaptiveProminentPrimaryButtonStyle: ButtonStyle {
    @Environment(\.colorScheme) private var colorScheme
    @Environment(\.isEnabled) private var isEnabled
    
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .buttonStyle(.borderedProminent)
            // 启用态根据配色模式切换tint和文字颜色,禁用态保留primary tint
            .tint(isEnabled ? (colorScheme == .dark ? .white : .black) : .primary)
            .foregroundColor(isEnabled ? (colorScheme == .dark ? .black : .white) : nil)
            // 模拟原生按钮的按压透明度变化
            .opacity(configuration.isPressed ? 0.8 : 1)
    }
}

使用方式

直接给按钮应用自定义样式即可:

Button("操作按钮") {
    // 点击逻辑
}
.buttonStyle(AdaptiveProminentPrimaryButtonStyle())
// 禁用状态会自动沿用primary的原生配色
.disabled(false)

这个方案的优势:

  • 仅通过环境变量判断配色模式,没有冗余的条件语句
  • 禁用状态完全保留系统原生的primary配色逻辑
  • 自定义样式可以全局复用,避免重复代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:41:06