【问题标题】:How to change icon's color of selected tab bar item in SwiftUI?如何更改 SwiftUI 中所选选项卡栏项目的图标颜色?
【发布时间】:2022-12-20 19:49:19
【问题描述】:

我尝试使用 UITabBar.appearance().unselectedItemTintColor 更改图标的颜色,但它仅适用于 systemImage 并且不突出显示图像,仅突出显示文本。

init() {
   UITabBar.appearance().unselectedItemTintColor = .secondaryLabel 
}

TabView {
        FirstView()
            .tabItem {
                Text("Home")
                Image("home")
            }
            
        CatalogView()
            .tabItem {
                
                Text("Categories")
                Image("catalog")
                    
            }
        
        CustomerProfileView()
            .tabItem {
                Text("Profile")
                Image("profile")
            }
           
            
        ShoppingView()
            .tabItem {
                Text("Cart")
                Image("shoppingbasket")
            }  
    }

我也试过 .accentColor 但 Xcode 说它将被弃用。

【问题讨论】:

  • this 是否回答了您的问题?
  • @Yrb 嗨!我尝试了 UITabBar.appearance().tintColor 和 UITabBar.appearance().barTintColor 但它没有突出显示图标

标签: swiftui uitabbarcontroller


【解决方案1】:

在这种情况下,您可以使用foregroundColor

Image("shoppingbasket")
    .renderingMode(.template)
    .foregroundColor(Color(.secondaryLabel))

【讨论】:

  • 谢谢!现在它终于也突出显示了图标。
【解决方案2】:

您的代码工作正常。

init() {
   UITabBar.appearance().unselectedItemTintColor = .secondaryLabel 
}

但是您还需要将您的资产设置为资产目录中的模板图像:

所以不需要使用 .foregroundColor

【讨论】: