Search code examples
iosswiftuisearchbar

Is there a way to only activate the cancel button on a search bar while editing?


I know you can do this with the clear button on a text field like this:

searchController?.searchBar.searchTextField.clearButtonMode = .whileEditing

But is there something similar for the cancel button on a search bar?

searchController?.searchBar.showsCancelButton = true // this exists
searchController?.searchBar.cancelButtonMode = .whileEditing // I could not find this

Cancel Button

Thank you!


Solution

  • If you don't want the search bar to appear until the user actually taps on the search bar of the search controller, don't add any code for the cancel button. The default behavior is to not show the cancel button until the user activates search.

    Simply remove any code you have to setup or change the cancel button.

    As of iOS 13 you can use the automaticallyShowsCancelButton property of UISearchController but in iOS it defaults to true. It seems to default to false under Mac Catalyst.