我拼命地试图让我的标签栏颜色尊重当前的配色方案。
当应用程序启动时,颜色是正确的。但是如果我切换深色和浅色模式,颜色不会切换回正确的颜色。始终应用灯光模式颜色。代码位于图像下方(为演示进行了简化)。
颜色在 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"))
}
}
关于SwiftUI 2.0 - TabView 标签栏颜色不符合当前的配色方案(深色或浅色模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66445366/