SwiftUI 2.0 - TabView 标签栏颜色不符合当前的配色方案(深色或浅色模式)

标签 swiftui tabbar tabview

我拼命地试图让我的标签栏颜色尊重当前的配色方案。
当应用程序启动时,颜色是正确的。但是如果我切换深色和浅色模式,颜色不会切换回正确的颜色。始终应用灯光模式颜色。代码位于图像下方(为演示进行了简化)。
Dark mode tab bar with correct colors
Light mode tab bar with correct colors
Dark mode tab bar with wring colors
颜色在 Assets.xcassets 中指定目录(任何/浅色/深色)。
enter image description here

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/

相关文章:

ios - 为什么在 SwiftUI 的 TabView 中切换选项卡时 onDisappear 之后再次调用 onAppear?

ios - 如何在 SwiftUI 的 TabView 中添加底部曲线?

SwiftUI 预览错误 - "Cannot preview in this file - Update failed"

SwiftUI Charts 如何向选定(或最后一个)BarMark 添加指示线

iphone - 检查 tabBar 在 iOS 应用程序上是否可见

ios - 快速如何推回导航 View 控件

ios - ios 标签栏触摸和触摸手势的奇怪错误

iOS 从多个 View 访问数据

SwiftUI 全屏 UIImagePickerController(相机)

search - SwiftUI - 单击取消时执行操作 - .searchable 函数