SwiftUI切换标签栏背景为深色时如何修改标签项边框颜色?
实现方案
这个需求完全可以实现,你只需要在现有修改TabBar背景色的逻辑中,同步调整未选中标签项的配色即可。
核心修改逻辑
UITabBar 自带 unselectedItemTintColor 属性,专门用于控制未选中状态下的标签项图标、文字颜色,你可以在切换背景色的同时修改这个属性,选中状态的蓝色不需要额外调整,保持默认即可。
修改后完整代码
struct DemoView: View { let tabBar = UITabBar.appearance() init() { tabBar.barTintColor = UIColor.black // 初始化未选中项配色,和后续逻辑保持一致 tabBar.unselectedItemTintColor = .red } @State private var selectedTab = 0 // 记录当前选中的标签 var body: some View { TabView(selection: $selectedTab) { Text("FirstView") .tabItem{ Image(systemName: "homekit") Text("First") }.tag(0) Text("SecondView") .tabItem{ Image(systemName: "heart") Text("Second") }.tag(1) Text("ThirdView") .tabItem { Image(systemName: "video") Text("Third") }.tag(2) } .onAppear { setTabViewBackground() } .id(selectedTab) } func setTabViewBackground() { let isDarkBackground = selectedTab != 0 tabBar.barTintColor = isDarkBackground ? .black : .white // 同步修改未选中标签项配色 tabBar.unselectedItemTintColor = isDarkBackground ? .red : .systemGray // 若需要兼容iOS15+,可添加以下代码避免滚动时样式失效 let appearance = UITabBarAppearance() appearance.backgroundColor = isDarkBackground ? .black : .white appearance.stackedLayoutAppearance.normal.iconColor = isDarkBackground ? .red : .systemGray appearance.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: isDarkBackground ? UIColor.red : UIColor.systemGray] appearance.stackedLayoutAppearance.selected.iconColor = .systemBlue appearance.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor.systemBlue] tabBar.standardAppearance = appearance if #available(iOS 15.0, *) { tabBar.scrollEdgeAppearance = appearance } } }
效果说明
- 选中第一个标签时:TabBar背景为白色,未选中标签显示灰色,选中标签保持蓝色,和原有默认效果一致
- 选中其他标签时:TabBar背景为黑色,未选中标签显示红色,选中标签仍保持蓝色,完全符合需求
内容的提问来源于stack exchange,提问作者user16098302
相关产品推荐
相关产品推荐

