简体   繁体   English

根据选择的选项卡更改 Tabview 颜色 -Swiftui

[英]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.目前,我可以使用 init 中的以下代码使 tabview 栏清晰。

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.试图在主体重绘时触发 func,如果它的这种声明式风格对我来说是最好的,但根本不会改变 tabview 背景。

Any .appearance affects instances created after the appearance itself.任何.appearance影响在外观本身之后创建的实例。 So the solution is to re-create TabView after appearance configuration changed.所以解决方案是在外观配置更改后重新创建TabView

Here is a demo of approach.这是方法的演示。 Tested with Xcode 12 / iOS 14.用 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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