Reputation: 1095
How can i change color of unselected icon (on screenshot) in TabView (SwiftUI)? Because this icon is invisible
Upvotes: 9
Views: 7575
Reputation: 1908
Another option is to make sure your image has the desired color for the unselected state, track which item is selected and then toggle rendering mode .template
for it.
// Create helper extension
extension Image {
@ViewBuilder
fileprivate func setRenderingMode(selected: Bool) -> some View {
if selected {
self.renderingMode(.template)
} else {
self.renderingMode(.original)
}
}
}
// Then in your TabView
struct MyTab: View {
enum TabItem {
case tab1
case tab2
case tab3
}
@State var selectedTab = TabItem.tab1
var body: some View {
TabView(selection: $selectedTab) {
Text("Tab Content 1")
.tabItem {
Image("tabimage1")
.setRenderingMode(selected: selectedTab == .tab1)
}.tag(TabItem.tab1)
Text("Tab Content 2")
.tabItem {
Image("tabimage2")
.setRenderingMode(selected: selectedTab == .tab2)
}.tag(TabItem.tab2)
Text("Tab Content 3")
.tabItem {
Image("tabimage3")
.setRenderingMode(selected: selectedTab == .tab3)
}.tag(TabItem.tab3)
}.tint(Color.red)
}
}
What this does is that when selected, the rendering mode changes to template therefore tinting the image with the tint color. When not selected, it renders in the default color (e.g. black).
Upvotes: 2
Reputation: 258541
You can use TabBarAccessor
from my solution to Programmatically detect Tab Bar or TabView height in SwiftUI to change what you need as in below demo.
Tested with Xcode 11.4 / iOS 13.4
TabView {
Text("First View")
.background(TabBarAccessor { tabBar in
tabBar.unselectedItemTintColor = UIColor.red
})
.tabItem { Image(systemName: "1.circle") }
.tag(0)
Text("Second View")
.tabItem { Image(systemName: "2.circle") }
.tag(1)
}
Update: alternate via appearance also works
init() {
UITabBar.appearance().unselectedItemTintColor = UIColor.green
}
Upvotes: 14