NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to conditionally change ToolbarItem color?

Forums > SwiftUI

With the following code, I can conditionally assign different colors to navigationTitle text.

init() {
    //Use this color when UINavigationBar shows large title (unscrolled)
    UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.blue]

    //Use this color when UINavigationBar shows inline title (scrolled down
    UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.green]
}

And I wanted to do the same for toolbar items, but couldn't figure out how.

I can set the "general" color of toolbar items like below, but I'm having trouble conditionally assigning different colors to toolbar items depending on if the NavigationBar is in largeTitle mode or inline title mode. Any leads would be helpful, thank you!

ToolbarItem(placement: .navigationBarTrailing) {
    HStack(spacing: 20) {
        Button {
          // button action
        } label: {
            Image(systemName: "location.circle.fill")
                .foregroundColor(.green)
        }
        Button {
            // button action
        } label: {
            Image(systemName: "gear")
                .foregroundColor(.green)
        }
    }
}

   

Hacking with Swift is sponsored by Stream

SPONSORED Build Chat messaging quickly with Stream Chat. The Stream iOS Chat SDK is highly flexible, customizable, and crazy optimized for performance. Take advantage of this top-notch developer experience, get started for free today!

Click here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.