Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchBar x button pressed

How handle the event when press the 'x' button?

I try this method but not works.

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{

}

enter image description here

like image 547
Fabio Avatar asked Mar 19 '15 01:03

Fabio


5 Answers

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.

like image 141
Eric Johnson Avatar answered Nov 13 '22 08:11

Eric Johnson


A rather hacky way to do it but this works.

private var didTapDeleteKey = false

func 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.

like image 32
funct7 Avatar answered Nov 13 '22 09:11

funct7


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)
}
like image 19
Kedar Sukerkar Avatar answered Nov 13 '22 09:11

Kedar Sukerkar


Simplest solution in Swift 5.0

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText.isEmpty {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            searchBar.resignFirstResponder()
        }
    }
}
like image 9
Dejan Avatar answered Nov 13 '22 07:11

Dejan


I had the same issue, tried to solve it with accessing searchBar's subview textField but it caused my app crash, and with a last effort i found this post.

Another issue was that,

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

is being called twice when cancel button clicked, see also this.

And lastly what i did is;

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (![searchText isEqualToString:self.searchText]) {
        self.searchText = searchText;
        return;
    }
    NSLog(@"Clear clicked");
}

This solved my issue.

like image 4
Eray Diler Avatar answered Nov 13 '22 08:11

Eray Diler