15

Is there any way to change the image of a tab item in SwiftUI's TabbedView when it's selected or unselected?

TabbedView(selection: $selection) {
  Text("Home").tabItem {
    Image(systemName: "house")
    Text("Home")
  }.tag(0)

  Text("Away").tabItem {
    Image("away")
    Text("Away")
  }.tag(1)
}

I've tried searching on the web but no answers were found. I'm using Xcode 11 beta 4.

da1
  • 487
  • 5
  • 10

1 Answers1

40

You can use a conditional/ternary operator and render an image depending on the $selection

see example:

struct ContentView: View {
    @State private var selection = 0

    var body: some View {
        TabView(selection: $selection) {
            Text("Home")
                .tabItem {
                    selection == 0 ? Image(systemName: "house.fill") : Image(systemName: "house")
                    Text("Home")
                }
                .tag(0)

            Text("Away")
                .tabItem {
                    selection == 1 ? Image(systemName: "a.circle.fill") : Image(systemName: "hand.raised.fill")
                    Text("Away")
                }
                .tag(1)
        }
    }
}
Edward
  • 2,864
  • 2
  • 29
  • 39
jkusachi
  • 726
  • 7
  • 9