Changing the color of .searchable() elements
Asked Answered
C

1

5

I am using the .searchable() modifier on a NavigationStack. I want to change the color of the cancel button as it does not match with my app colors. How can I do this?

This is what I already tried without luck: accentcolor, tint, foregroundcolor, background change following the .searchable() adding dark theme with .preferredColorScheme(.dark) following .searchable (only changes the color of the textbar adding UINavigationBar.appearance().tintColor = .white or UISearchBar.appearance().overrideUserInterfaceStyle = .dark to the init of the app

I thought about creating a Zstack to make a box with my own text to cover the cancel button but this sounds like a lot of work as the cancel button moves with animation when the textfield is clicked. And it will vary depending on device orientation and type of device.

Any advice would be helpful!

Chrominance answered 3/8, 2023 at 7:52 Comment(1)
Using UISearchBar.appearance().tintColor = UIColor(red: 0/255, green: 70/255, blue: 65/255, alpha: 1.0) in the init changes the color of the cancel button as desired within the rgb scaleChrominance
L
7

You should add tint to the navigation stack/split view, not the searchable view.

e.g.

@State var search = ""

var body: some View {
    NavigationStack {
        List {
            Text("Foo")
            Text("Bar")
        }
        .searchable(text: $search)
    }.tint(Color.red)
}

The "Cancel" button would appear red.

As an alternative, you can also change the "AccentColor" color in your asset catalog. That changes the tint of all the views where you have not specified a .tint(...), including the "Cancel" button of a search bar.

Note that this also changes the tint of the toolbar items in the navigation bar, but you can easily override that by adding your own tints to the tool bar items.

.toolbar {
    ToolbarItem(placement: .navigation) {
        Button("Foo") { ... }
            .tint(Color.blue)
    }
}
Luthuli answered 3/8, 2023 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.