Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 271
da1 Avatar asked Jul 22 '19 06:07

da1


1 Answers

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)
        }
    }
}
like image 140
jkusachi Avatar answered Oct 14 '22 01:10

jkusachi