32

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

Anjali Kevadiya
  • 3,567
  • 4
  • 22
  • 43

3 Answers3

73

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

Procrastin8
  • 4,193
  • 12
  • 25
  • 1
    This also affects elements within the `View` such as `Button`s though. – M3nd3z Jan 22 '21 at 09:55
  • This sis bad way. This works with only systemIcons. If u provide custom icon this wont work their. – Kudos May 07 '21 at 12:20
  • 2
    You're probably not setting up your `renderingMode` properly or your icon doesn't use transparency like it should. – Procrastin8 May 08 '21 at 13:11
  • 1
    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. – Lord Zsolt Apr 25 '22 at 20:16
  • 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. – Procrastin8 May 18 '22 at 11:23
0

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)
Michael Wang
  • 9,583
  • 1
  • 19
  • 17
0

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))
Lawrence Gimenez
  • 2,662
  • 4
  • 34
  • 52