In my app I have 2 tabs.
First tab view has white background.
Second tabView has black background.
Because of that I would like to change tabbar style depending on what TabBarItem selected
When tab1 is selected, I would like tab bar icons color to be:
selected - black, unselected - grey
When tab2 is selected, I would like to change colors to:
selected - white, unselected - grey
I'm able to change icon color with accentColor
property like that:
TabView {
FirstTabView()
.tabItem {
Image("tab1").renderingMode(.template)
}
SecondTabView()
.tabItem {
Image("tab2").renderingMode(.template)
}
}.accentColor(.white)
But how to change icon color when user click on second tab ?
I tried something like that:
@State private var selection = 0
TabView(selection: $selection) {
FirstTabView()
.tabItem {
Image("tab1").renderingMode(.template)
}
SecondTabView()
.tabItem {
Image("tab2").renderingMode(.template)
}
}.accentColor(selection == 0 ? .black : .white)
But it doesn't work
CodePudding user response:
To update tab items TabView
should be rebuilt, so try
Here is a full demo (colors changed for better visibility). Tested with Xcode 13 / iOS 15
struct DemoView: View {
@State private var selection = 0
var body: some View {
TabView(selection: $selection) {
Text("FirstTabView")
.tabItem {
Image(systemName: "1.circle").renderingMode(.template)
}.tag(0)
Text("SecondTabView")
.tabItem {
Image(systemName: "2.circle").renderingMode(.template)
}.tag(1)
}
.accentColor(selection == 0 ? .red : .blue)
.id(selection) // << here !!
}
}