【问题标题】:SwiftUI 2.0 - TabView tab bar colors don't respect the current color scheme (dark or light mode)SwiftUI 2.0 - TabView 标签栏颜色不尊重当前配色方案(深色或浅色模式)
【发布时间】:2021-06-01 08:22:54
【问题描述】:

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

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

【问题讨论】:

  • 您应该通过 Assets.xcassets 中的颜色来解决问题吗?我的意思是你希望 Colors 了解新的 ColorScheme 并做出改变,这是你想要的唯一方式吗?

标签: swiftui tabbar tabview


【解决方案1】:

通过将标签项着色作为 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"))
  }
}

【讨论】:

  • 谢谢!删除 UITabBar.appearance().isTranslucent = true, UITabBar.appearance().tintColor = UIColor(named: "TabBarTint") 和 UITabBar.appearance().backgroundColor = UIColor(.skipperTabBar) 解决了这个问题!
猜你喜欢
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
  • 2020-08-31
  • 2020-04-13
  • 2014-07-06
  • 2019-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多