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

如何在Xcode 14中修改Tab Bar颜色并集成到SwiftUI代码中?

在Xcode 14的SwiftUI中修改Tab Bar颜色的方法

先修正你代码里的拼写错误

你代码中TabView(selection: $Selection)的$Selection是大写,和@State private var selection = 1的变量名大小写不一致,会导致编译错误,需要改成$selection。


1. 修改Tab Bar选中项的颜色

你已经用到了.accentColor(Color("Green")),这个方法在Xcode14(对应iOS15/16)依然有效,修正拼写错误后,选中的Tab图标和文字会自动应用你定义的Green颜色。

修改后的基础代码片段:

TabView(selection: $selection) {
    Home()
        .tabItem { Label("Home", systemImage: "house.fill") }.tag(1)
    About()
        .tabItem { Label("About", systemImage: "person.crop.circle") }.tag(2)
    Products()
        .tabItem { Label("Products", systemImage: "bag.fill") }.tag(3)
    Gallery()
        .tabItem { Label("Gallery", systemImage: "photo.on.rectangle") }.tag(4)
    Contact()
        .tabItem { Label("Contact", systemImage: "phone.bubble.left.fill") }.tag(5)
}
.accentColor(Color("Green"))

2. 修改Tab Bar的背景颜色

适配iOS16+(Xcode14原生支持)

直接用SwiftUI修饰符设置:

TabView(selection: $selection) {
    // 各个Tab页面
}
.accentColor(Color("Green"))
// 设置Tab Bar背景色
.toolbarBackground(Color("TabBarBg"), for: .tabBar)
// 确保页面滚动时背景色不会消失
.toolbarBackground(.visible, for: .tabBar)

兼容iOS15

通过UIKit外观代理设置,在你的App结构体的init方法中添加:

init() {
    UITabBar.appearance().backgroundColor = UIColor(Color("TabBarBg"))
}

3. 修改未选中项的图标/文字颜色

方法一:SwiftUI原生实现(iOS16+)

给每个tabItem添加foregroundStyle,结合环境变量判断选中状态:

.tabItem {
    Label("Home", systemImage: "house.fill")
        .foregroundStyle(.isSelected ? Color("Green") : Color.gray)
}

方法二:UIKit外观代理(兼容iOS15)

在App结构体的init方法中添加:

init() {
    UITabBar.appearance().unselectedItemTintColor = UIColor.gray
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:33:26