Search code examples
iosswiftuixcode11

SwiftUI: How to change the image for a selected item in TabbedView


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.


Solution

  • 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)
            }
        }
    }