Change Tabview color based on which tab is selected -Swiftui

喜欢而已 提交于 2021-02-05 07:09:39

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/63404238/change-tabview-color-based-on-which-tab-is-selected-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!