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

为什么SwiftUI工具栏内按钮的图片背景无法正常显示?

问题核心原因

SwiftUI 导航栏的工具栏会默认给内部所有按钮应用系统自带的边框less按钮样式,强制使用导航栏全局色调,覆盖了你自定义的背景、前景色配置,导致选中状态的样式无法正常展示。

解决方案

给自定义按钮添加.buttonStyle(.plain)禁用系统默认样式即可,同时可以优化代码结构让逻辑更简洁,自动适配明暗模式:

修改后的自定义开关按钮代码

struct ToggleButtonView: View {
    // 若需要外部控制状态可使用@Binding,仅内部使用保留@State也可
    @Binding var isOn: Bool

    var body: some View {
        Button(action: {
            isOn.toggle()
        }, label: {
            Image(systemName: "list.bullet.below.rectangle")
                .foregroundColor(isOn ? Color(.systemBackground) : .accentColor)
                .padding(6)
                .background(
                    RoundedRectangle(cornerRadius: 5)
                        .fill(isOn ? Color.accentColor : .clear)
                )
        })
        // 核心:禁用系统默认按钮样式,完全保留自定义配置
        .buttonStyle(.plain)
    }
}

工具栏调用代码

struct TestView: View {
    @State private var toggleIsOn = false
    
    var body: some View {
        // iOS16及以上推荐用NavigationStack,低版本可保留NavigationView
        NavigationStack {
            ScrollView {
                ForEach(0..<5) { number in
                    Text("Number \(number)")
                }
            }
            .toolbar {
                ToolbarItemGroup(placement: .navigationBarTrailing) {
                    ToggleButtonView(isOn: $toggleIsOn)
                
                    Button(action: {}, label: {
                        Image(systemName: "plus")
                    })
                }
            }
            .navigationTitle("Plz halp")
        }
        // iOS15及以上用tint替代accentColor更符合规范
        .tint(.red)
    }
}

补充说明

优化后的代码合并了重复的Image声明,通过状态动态切换颜色和背景,切换时自带的淡入淡出动画和苹果原生日历的交互效果完全一致,且使用系统语义色自动适配浅色、深色模式,无需额外适配逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 18:54:00