Search code examples
xcodeswiftuisearchableswiftui-navigationstack.searchable

Changing the color of .searchable() elements


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!


Solution

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