update TabView background color

I can use this code to change the background color of the tab bar:

    let appearance = UITabBarAppearance()
    appearance.backgroundColor = UIColor(bgColor)
    let appearance2 = UITabBar.appearance()
    appearance2.scrollEdgeAppearance = appearance
    appearance2.standardAppearance = appearance

But it seems this is a one-time thing. If I run this code again later with a different value of bgColor, it does not change. What can I do to modify the tab bar background color after I have set the color once? I need this because I am allowing the user to change it.

Because you are using a UIKit API in SwiftUI in an “unnatural“ way, I won’t work as expected. You’re right about it being sort of a one-time thing. Even Apple recommends staying away from this method:

In general, you should not rely on implementation details of a framework (including SwiftUI) to achieve specific behaviors in your apps.


In iOS 16, SwiftUI does gain a new modifier: toolbarBackground(_:for:). You can use it like this:

...
.toolbarBackground(.red, for: .tabBar)

I believe it only applies to the current view, so you can change the behavior at different levels of the hierarchy.


See the documentation as there is a lot more you can customise now regarding bars.

I would prefer to use a SwiftUI only approach if there is one. If not, I prefer to use UIKit in the most natural way I can. What would you recommend if I can't require iOS 16 yet? The key requirement is that I need to be able to set the tab bar background color when the app starts AND change it later based on user interaction. Is the answer that it can't be done without iOS 16?

I landed on a solution where I set the background color of the TabView to clear with this:

        UITabBar.appearance().backgroundColor = .clear

Then I added a background color that is the color I want for the entire screen, including the TabView with this:

        ZStack {
            Color.fromJSON(backgroundColor).ignoresSafeArea()
            VStack(alignment: .leading) {
                content()
                    .padding(.horizontal)
                Spacer() // pushes content to top
            }
        }

Of course one could position a Color behind only the tab bar to change the background color of just that part of the screen.

update TabView background color
 
 
Q