简体   繁体   中英

SwiftUI: TabView dynamic accentColor

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

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

    }
}

backup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM