SwiftUI 2.0 - TabView 选项卡栏颜色不符合当前配色方案(深色或浅色模式)

SwiftUI 2.0 - TabView tab bar colors don't respect the current color scheme (dark or light mode)

我拼命想让我的标签栏颜色符合当前的配色方案。 当应用程序启动时,颜色是正确的。但是,如果我切换深色和浅色模式,颜色不会切换回正确的颜色。始终应用灯光模式颜色。代码位于图像下方(为演示进行了简化)。

颜色在 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"))
  }
}