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

SwiftUI配置TabBar未选中项颜色、始终显示及Home Indicator颜色

解决SwiftUI TabBar样式冲突与Home Indicator颜色自定义问题

一、解决TabBar未选中颜色与.toolbarBackground的冲突

直接用UITabBarAppearance统一配置TabBar全量样式,替代单独修改UITabBar.appearance(),既能保留.toolbarBackground让TabBar始终显示,又能正确设置未选中标签颜色:

struct ContentView: View {
    init() {
        let tabBarAppearance = UITabBarAppearance()
        // 设置TabBar背景色
        tabBarAppearance.backgroundColor = UIColor.darkGray
        
        // 配置选中标签的图标和文字颜色
        tabBarAppearance.stackedLayoutAppearance.selected.iconColor = .orange
        tabBarAppearance.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor.orange]
        
        // 配置未选中标签的图标和文字颜色(解决深色背景下辨识度问题)
        tabBarAppearance.stackedLayoutAppearance.normal.iconColor = .lightGray
        tabBarAppearance.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor.lightGray]
        
        // 将样式应用到标准状态和滚动边缘状态
        UITabBar.appearance().standardAppearance = tabBarAppearance
        UITabBar.appearance().scrollEdgeAppearance = tabBarAppearance
    }
    
    var body: some View {
        TabView {
            Text("首页")
                .tabItem {
                    Image(systemName: "house.fill")
                    Text("首页")
                }
            Text("我的")
                .tabItem {
                    Image(systemName: "person.fill")
                    Text("我的")
                }
        }
        // 保持TabBar始终可见
        .toolbarBackground(Color.darkGray, for: .tabBar)
        .toolbarBackground(.visible, for: .tabBar)
    }
}

二、统一设置选中标签颜色

上述代码已通过UITabBarAppearance的stackedLayoutAppearance配置了选中状态的颜色,无需单独在init中设置tintColor,直接解决之前无法通过tintColor设置选中颜色的问题。

三、自定义Home Indicator颜色(仅TabBar显示时为白色)

SwiftUI无直接修改Home Indicator颜色的API,可通过监听TabView的显示/隐藏事件,修改应用窗口的tintColor实现:

  1. 添加UIApplication扩展,方便获取当前活跃窗口:
extension UIApplication {
    var keyWindow: UIWindow? {
        connectedScenes
            .filter { $0.activationState == .foregroundActive }
            .first(where: { $0 is UIWindowScene })
            .flatMap({ $0 as? UIWindowScene })?.windows
            .first(where: \.isKeyWindow)
    }
}
  1. 在TabView中添加状态监听:
TabView {
    // 你的标签页内容
}
// ... 保留之前的toolbarBackground配置
.onAppear {
    // 显示TabBar时,将Home Indicator设为白色
    UIApplication.shared.keyWindow?.tintColor = .white
}
.onDisappear {
    // 离开TabView时恢复默认颜色
    UIApplication.shared.keyWindow?.tintColor = nil
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 22:03:24