Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SwiftUI: TabView dynamic accentColor

In my app I have 2 tabs.

First tab view has white background.

Second tabView has black background.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

demo

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 !!

    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading