简体   繁体   中英

Change Tabview color based on which tab is selected -Swiftui

I am trying to see if I can make the color of the bottom tabview change depending on which tab item is selected. Currently I can make the tabview bar clear with the below code in the init.

let tabBar = UITabBar.appearance()
    init() {
        tabBar.barTintColor = UIColor.clear
        tabBar.backgroundImage = UIImage()
        tabBar.shadowImage = UIImage()
    }
 ...
 TabView(selection: $selectedTab) {
                FirstView()
                    .tabItem{
                        Text("First")
                    }
                SecondView()
                    .tabItem{
                        Text("Second")
                    }
    }
    .onAppear{
setTabViewBackground()
}

func setTabViewBackground() {
        if selectedTab != 0 {
            tabBar.barTintColor = UIColor.blue
        }
    }

Tried to just fire the func when the body redraws and idk if its this declarative style that's getting the best of me but doesn't change the tabview background at all.

Any .appearance affects instances created after the appearance itself. So the solution is to re-create TabView after appearance configuration changed.

Here is a demo of approach. Tested with Xcode 12 / iOS 14.

演示

struct DemoView: View {

    let tabBar = UITabBar.appearance()

    init() {
        tabBar.barTintColor = UIColor.red
    }

    @State private var selectedTab = 0    // preserves selected tab

    var body: some View {
        TabView(selection: $selectedTab) {
            Text("FirstView")
                .tabItem{
                    Text("First")
                }.tag(0)
            Text("SecondView")
                .tabItem{
                    Text("Second")
                }.tag(1)
        }
        .onAppear {
            setTabViewBackground()  // called, because `id` is below
        }
        .id(selectedTab)   // recreates entire above view with new tabbar
    }

    func setTabViewBackground() {
        tabBar.barTintColor = selectedTab != 0 ? .blue : .red
    }
}

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