UISearchBar x button pressed UISearchBar x button pressed xcode xcode

UISearchBar x button pressed


I don't think there's an easy way to hook into the X button.

However, you can hook into its direct consequence: cleared text.

Try this:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {    if searchText == "" {        print("UISearchBar.text cleared!")    }}

The side effect is this also gets called when you manually clear your text.


A rather hacky way to do it but this works.

private var didTapDeleteKey = falsefunc searchBar(_ searchBar: UISearchBar,               shouldChangeTextIn range: NSRange,               replacementText text: String) -> Bool{    didTapDeleteKey = text.isEmpty    return true}func searchBar(_ searchBar: UISearchBar,               textDidChange searchText: String){    if !didTapDeleteKey && searchText.isEmpty {        // Do something here    }    didTapDeleteKey = false}

The success of this code hinges on the fact that when tapping the clear button of the search bar, searchBar(_:shouldChangeTextIn:replacementText:) -> Bool is not called. Instead when the delete button of the keyboard is tapped, the method is called.


Swift 5.2, Xcode 11.4

This one worked for me.

if let searchTextField = self.categoriesSearchBar.value(forKey: "searchField") as? UITextField , let clearButton = searchTextField.value(forKey: "_clearButton")as? UIButton {     clearButton.addTarget(self, action: #selector(self.yourFunction), for: .touchUpInside)}