0

Given

TabView {
    WelcomeView()
        .tabItem {
            Label("Home", systemImage: "house")
        }
}        

renders the TabView in the default color and, when active, the highlighted color:

an unhighlighted house and active: a highlighted house

I would like to change the icon to another one when highlighted instead, like house.circle, and not using the accent color, for leanness, like so:

a circled house

Is there a smart way I am missing to use the default TabView behavior and not rebuild its logic and state handling? I would like to keep the code as simple as possible since I am a bloody beginner.

Thanks y'all for your help!

Adrian Föder
  • 770
  • 1
  • 7
  • 22
  • I never tested, but may be you can try to add a test when setting the image name like : systemImage: selectedTab == 2 ? " home.circle" : "home" – Ptit Xav Mar 25 '23 at 19:30

1 Answers1

1

You can use "selection" property of TabView to change image and "gray" color as accentColor. The following code may help you.

import SwiftUI

struct Sample: View {
    @State private var selection = true
    var body: some View {
        TabView(selection: $selection) {
            Text("Home")
                .tabItem {
                    if selection == true {
                        Image(systemName: "house.circle")
                    }
                    else {
                        Image(systemName: "house")
                    }
                    Text("Home")
                }
                .tag(true)
            Text("Sign UP")
                .tabItem {
                    if selection == false {
                        Image(systemName: "person")
                    }
                    else {
                        Image(systemName: "person.2.slash")
                    }
                    Text("Account")
                }
                .tag(false)
        }
        .accentColor(.gray)
    }
}
  • Thank you! I used an enum to represent the selected Tag which feels cleaner than using a boolean, but you've definitely solved my issue. I also used the ternary operator for the Image definition (like `systemName: selection ? "house.circle" : "house"`) – Adrian Föder Mar 28 '23 at 08:46