1

How can I make a different tab item for selected and unselected tabs? For example, I would like to use a different image and make the selected text bold.

This is what I have:

struct ContentView: View {
    @SceneStorage("selectedTab") private var selectedTab = 0

    var body: some View {
        TabView(selection: $selectedTab) {
            Text("Content 1")
                .tabItem {
                    Label("First", systemImage: "alarm")
                        .accessibilityHint("Something 1")
                }
            Text("Content 2")
                .tabItem {
                    Label("Second", systemImage: "calendar")
                        .accessibilityHint("Something 2")
                }
        }
    }
}

Is there a way a built in way to do this since inside the tab I can't figure out if it is the selected one or not.

TruMan1
  • 33,665
  • 59
  • 184
  • 335

1 Answers1

3

Use selectedTab with tag and change your tab image by using the selectedTab condition.

And for Font you can use UITabBarAppearance().

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

    init() {
        // Set font here of selected and normal
        let appearance = UITabBarAppearance()
        appearance.stackedLayoutAppearance.normal.titleTextAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10)]
        appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15)]
        UITabBar.appearance().standardAppearance = appearance
    }
    
    var body: some View {
        TabView(selection: $selectedTab) {
            Text("Content 1")
                .tabItem {
                    Label("First", systemImage: selectedTab == 0 ? "alarm" : "alarm_unselected") //<-- Here
                        .accessibilityHint("Something 1")
                }.tag(0) //<-- Here
            Text("Content 2")
                .tabItem {
                    Label("Second", systemImage: selectedTab == 1 ? "calendar" : "calendar_unselected") //<-- Here
                        .accessibilityHint("Something 2")
                }.tag(1) //<-- Here
        }
    }
}
Raja Kishan
  • 16,767
  • 2
  • 26
  • 52