Change the tab selection color in TabBar SwiftUI
Asked Answered
A

3

35

I am trying to change the color of selected tab in TabBar, but nothing worked. I can change the TabBar backgroundColor by writing

struct ContentView: View {
    init() {
        UITabBar.appearance().backgroundColor = UIColor.purple
    }
    var body: some View { 
    }
}

In swift, we set tintColor and it does change the color of selected tab. But what do i need to do for swiftUI?

Here is my code,

    TabView(selection: $selection) {
        AView()
            .tabItem {
                VStack {
                    Image(systemName: "bubble.left.and.bubble.right")
                    Text("A Tab")
                }
        }.tag(0)

        BView()
            .tabItem {
                VStack {
                    Image(systemName: "house")
                    Text("B Tab")
                }
        }.tag(1)

        CView()
            .tabItem {
                VStack {
                    Image(systemName: "circle.grid.3x3")
                    Text("C Tab")
                }
        }.tag(2)
    }

Any help with this? Thanks in advance!!

Astrodynamics answered 21/8, 2019 at 21:1 Comment(0)
D
78

Use accentColor: https://developer.apple.com/documentation/swiftui/tabview/3368073-accentcolor

TabView {
  // fill this out with your tabbed content
}
.accentColor(.orange)

enter image description here

Deadandalive answered 21/8, 2019 at 21:43 Comment(5)
This also affects elements within the View such as Buttons though.Valenciavalenciennes
This sis bad way. This works with only systemIcons. If u provide custom icon this wont work their.Fowkes
You're probably not setting up your renderingMode properly or your icon doesn't use transparency like it should.Deadandalive
While this gets the job done, it will have very random effects on the rest of the code. It affects .navigationItem(leading: traling:) for example, so you need to explicitly add .tint to those items to counteract it. Not sure what else is impacted.Prognostic
The effects are not random in any way. Please look at the linked documentation to understand what it's doing. Probably more important to ask yourself why you want completely separate tab color vs app accent color.Deadandalive
H
2

It seems accentColor(_:) will be deprecated, if the deployment target is iOS 15 or above, we could use tint(_:) instead like below,

TabView {
    // custom tab item
}
.tint(.purple)
Hoehne answered 6/3, 2023 at 5:49 Comment(1)
this does not have any effect. Did anyone try that?Jaunitajaunt
E
2

For Xcode 15, another option is to use Assets

enter image description here

and you can use it in your code like

TabView {
    // custom tab item
}
.tint(Color(.tabAccent))
Exuberate answered 11/7, 2023 at 1:40 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.