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

SwiftUI中Toolbar背景颜色无法修改?如何设置为红色?

SwiftUI 修改 Toolbar 背景色为红色的解决方案

要修改SwiftUI中Toolbar的背景色,你需要使用toolbarBackground修饰符——普通的background修饰符无法对导航栏/工具栏生效,这是专门针对这类组件的背景设置方法。

修改后的完整代码

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                // Your content goes here
            }
            .navigationBarTitleDisplayMode(.inline)
            // 设置Toolbar背景为红色
            .toolbarBackground(.red, for: .navigationBar)
            // 可选:确保背景始终可见(滚动内容时也保持不透明)
            .toolbarBackground(.visible, for: .navigationBar)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    HStack {
                        Text("Kapoor Home")
                            .fontWeight(.semibold)
                            .foregroundColor(.black)
                        Image(systemName: "chevron.down")
                            .foregroundColor(.black)
                    }
                    .padding()
                }

                ToolbarItem(placement: .navigationBarTrailing) {
                    HStack {
                        Button(action: {
                            // Handle action for trailing item 1
                        }) {
                            Image(systemName: "plus")
                                .foregroundColor(.black)
                        }

                        Button(action: {
                            // Handle action for trailing item 2
                        }) {
                            Image(systemName: "bell.fill")
                                .foregroundColor(.black)
                        }
                    }
                    .padding()
                }
            }
            .navigationViewStyle(StackNavigationViewStyle())
            .background(Color.orange)
        }
    }
}
#Preview {
    ContentView()
}

关键说明

  • toolbarBackground(.red, for: .navigationBar):明确指定导航栏的背景颜色为红色,for: .navigationBar限定作用范围仅针对导航栏
  • toolbarBackground(.visible, for: .navigationBar):默认情况下页面内容滚动时导航栏背景会自动变透明,添加这一行可以让背景始终保持可见状态,不需要该效果可直接移除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:10:20