如何解决SwiftUI 2.0 - TabView 标签栏颜色不符合当前的配色方案深色或浅色模式
我拼命地尝试让我的标签栏颜色尊重当前的配色方案。 当应用程序启动时,颜色是正确的。但是如果我切换深色和浅色模式,颜色不会切换回正确的颜色。始终应用灯光模式颜色。代码在图片下方(为演示简化)。
颜色在 Assets.xcassets
目录中指定(任何/浅色/深色)。
import SwiftUI
struct TabBarColorTest: View {
@Environment(\.colorScheme) var colorScheme
init() {
UITabBar.appearance().isTranslucent = true
UITabBar.appearance().tintColor = UIColor(named: "TabBarTint")
UITabBar.appearance().unselectedItemTintColor = UIColor(named: "TabBarUnselected")
UITabBar.appearance().barTintColor = UIColor(named: "TabBar")
UITabBar.appearance().backgroundColor = UIColor(named: "TabBar")
}
var body: some View {
TabView {
Text("Zero")
.tabItem {
Label("Zero",systemImage: "0.square.fill")
}
Text("One")
.tabItem {
Label("One",systemImage: "1.square.fill")
}
}
.onChange(of: colorScheme,perform: { value in
UITabBar.appearance().isTranslucent = true
UITabBar.appearance().tintColor = UIColor(named: "TabBarTint")
UITabBar.appearance().unselectedItemTintColor = UIColor(named: "TabBarUnselected")
UITabBar.appearance().barTintColor = UIColor(named: "TabBar")
UITabBar.appearance().backgroundColor = UIColor(named: "TabBar")
})
}
}
struct TabBarColorTest_Previews: PreviewProvider {
static var previews: some View {
TabBarColorTest()
}
}
解决方法
通过将选项卡项的色调颜色作为 SwiftUI 修饰符并简化选项卡栏的 UIKIt 配置的初始化,问题应该得到解决。在 Xcode 12.4 上测试,iOS 14 作为最低目标。
struct ContentView: View {
init() {
UITabBar.appearance().barTintColor = .systemBackground
UITabBar.appearance().unselectedItemTintColor = UIColor(named: "TabBarUnselected")
}
var body: some View {
TabView {
Text("Zero")
.tabItem {
Label("Zero",systemImage: "0.square.fill")
}
Text("One")
.tabItem {
Label("One",systemImage: "1.square.fill")
}
}
.accentColor(Color("TabBarTint"))
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。