Adrian Föder
Adrian Föder

Reputation: 891

In a TabView/TabItem, how can I change the image for the highlighted item and don't use the accent color?

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!

Upvotes: 0

Views: 115

Answers (1)

Md. Ashikur Rahman
Md. Ashikur Rahman

Reputation: 97

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

Upvotes: 1

Related Questions