Dismissing keyboard from UISearchBar when the X button is tapped

uisearchcontroller x button
uisearchcontroller dismiss keyboard
uisearchbar x button clicked
dismiss keyboard swift
uisearchbar clear button click
dismiss keyboard on search swift
uisearchbar dismiss keyboard search button swift
search bar cross button action swift

I'm using the UISearchBar (but not the SearchDisplayController that's typically used in conjunction) and I'd like to dismiss the keyboard when you hit the 'X' button.

I've followed TomSwift's suggestion on getting called when the 'X' is tapped and that works great. But resigning first responder from the text field and also invoking in the UISearchBar instance, both with resignFirstResponder, won't make the keyboard go away.

Is there a way to get rid of the keyboard when the user has tapped the X button?

Here's what I did to get the 'Clear' notify:

- (void)viewDidLoad:
    for (UIView* v in searchBar.subviews)
        if ( [v isKindOfClass: [UITextField class]] )
            UITextField *tf = (UITextField *)v;
            tf.delegate = self;

Then I have my class setup to implement both UISearchBarDelegate and UITextFieldDelegate.

Having the class serve as the textfield delegate allows me to get this call:

- (BOOL)textFieldShouldClear:(UITextField *)textField
     [textField resignFirstResponder];
     [self.searchBar resignFirstResponder];
     return YES;

I've tried everything I can think of. The last thing I'm trying is to find a way to issue the 'searchBarCancelButtonClicked' that UISearchDelegate will invoke on my Controller class but not I'm sure how I could do this since the UISearchBar doesn't seem to have any direct methods to invoke with this name.


Well, this is a total hack but I was able to make it work. Basically the code invokes the handler for the cancel button. To make it work I had to invoke the selector with a delay, and I'm not sure why this had to be. Also, I had to write an accessor for the cancel button just like you did for the text field.

Again, this is a total hack. I'm not sure I'd do this myself in an app.

// this in the context of the search bar
- (UIButton*) cancelButton
    for (UIView* v in self.subviews)
        if ( [v isKindOfClass: [UIButton class]] )
            return (UIButton*)v;

    return nil;

// this is the textField delegate callback
- (BOOL)textFieldShouldClear:(UITextField *)textField
    [textField resignFirstResponder];

    UIButton* cb = _searchBar.cancelButton;

    NSObject* target = [[cb allTargets] anyObject];

    NSArray* actions = [cb actionsForTarget: target forControlEvent:UIControlEventTouchUpInside];

    NSString* selectorName = [actions  objectAtIndex:0];

    SEL selector = NSSelectorFromString( selectorName );

    [target performSelector: selector withObject: cb afterDelay: 0.1];

    return YES;

Original answer:

How do you get the clear 'X' button to display in the first place? In my test case I dont see it displaying...

Try doing a resignFirstResponder on the searchBar, not the textField.

Feasible to dismiss UISearchBar when the …, But resigning first responder from the text field and also invoking in the UISearchBar instance, both with resignFirstResponder , won't make the keyboard go away. Dismissing the keyboard with UISearchBar, without resigning first responder (4 answers) Closed 7 years ago . Hi i am using a UIsearchBar in my app, i tried all methods in UISearchBar Delegate to dismiss the keyboard but no use. could anyone help me out.

Toms answer got me thinking. If it is that the search bar is not yet the firstResponder when the user clicks the clear button we can just wait until it is, and then have it resignFirstResponder; i.e. along the lines of:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
  [self performFilteringBySearchText: searchText]; // or whatever

  // The user clicked the [X] button or otherwise cleared the text.
  if([searchText length] == 0) {
    [searchBar performSelector: @selector(resignFirstResponder) 
                    withObject: nil 
                    afterDelay: 0.1];

Works like a charm, and less hacky than Tom's IMHO.

UISearchBar x button pressed, I'm using the UISearchBar (but not the SearchDisplayController that's typically used in conjunction) and I'd like to dismiss the keyboard when you hit the 'X'� Call a function when the 'done' button is pressed on the keyboard in Cordova [duplicate] Dismissing keyboard from UISearchBar when the X button is tapped; iOS - close keyboard when button is pressed; Dismissing the keyboard for a UITextField in UIAlertView; How to set text color of a radio button when a button is pressed in Android?

This works:

[searchBar performSelector:@selector(resignFirstResponder) withObject:nil afterDelay:0.1];

Best way to dismiss Keyboard in a View Controller iOS (Swift), I'm using the UISearchBar without a Cancel button. When the user has tapped on the 'X' button, I'd like to hide the keyboard. Is there a way to� I need to know when the RPSystemBroadcastPickerView is tapped. Right now the UI is showing keyboard, which I want to keep showing (it is a chat app). However, the form showing the list of broadcast extensions to pick one is being shown under the keyboard. See following image: This effectively prevents the user to start the broadcast.

Updated for SWIFT 3:

Suppose that the user has entered a string in searchfield and clicks x the following code works to hide keyboard when x is pressed


func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) 
            if searchBar.text == nil || searchBar.text == ""
                searchBar.perform(#selector(self.resignFirstResponder), with: nil, afterDelay: 0.1)


SOLVED: TextField - Dismiss keyboard, uisearchbar dismiss keyboard search button search bar programmatically ios search bar swift clear search bar swift uisearchbar textfield delegate. How handle � Create the date picker and set it to the input views of the two text fields. Also create another view for the Done button and it as their accessory view. You will need that button to dismiss the input view. The Done button must be wired up to function which basically does this –

Swift 2 version:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        // The user clicked the [X] button or otherwise cleared the text.
        if (searchText.characters.count == 0) {
            searchBar.performSelector("resignFirstResponder", withObject: nil, afterDelay: 0.1)

Uitableview dismiss keyboard on tap, Best way to dismiss Keyboard in a View Controller iOS (Swift) this solution seems good enough but not all keyboards have return button. be better than tapping anywhere on the view controller to dismiss the keyboard. Thanks for sharing this. Very helpful. I had a followup question to what Ed has asked. I coded this in my app and it works when I first hit Search. The keyboard does go away. But now when i press the small x button on the right side of the search bar to delete the search text, the key board still remains and there is no way to make it go for

How do you keep the cancel button in the search bar enabled when , SOLVED: TextField - Dismiss keyboard - Clear button UIToolbar(frame: CGRect(x: 0, y: 0, width: textfield.frame.size.width, height: 44)) let UITextField{ @objc func doneButtonTapped(button:UIBarButtonItem) -> Void { self. Dismissing keyboard from textfield inside tableviewcell [duplicate] ios,objective-c,uitableview,keyboard,uitextfield This question already has an answer here: How to dismiss keyboard iOS programmatically 11 answers I have a custom tableViewCell which has a textfield inside. How to dismiss keyboard when tap any place outside the textfields?

UISearchBar "cancel" results in crash/index out of range : swift, 1 Feb 2020 Get code examples like "dismiss keyboard when tap outside recognizer to close the keyboard when user taps away I would like to dismiss the the Cancel button, clear existing text in search bar and hide the keyboard like this:. Swift 4, iPhone X support and Carthage fixes #287 ; Feature/epub title in navbar #281 (noxsicarius) Update realm to 3.0.2 #279 (noxsicarius) update Podfile.lock #277 (EmersonCarpes) 1.2.0 (2017-05-31) Full Changelog. Implemented enhancements: Crash if "Cannot read container.xml" #164; Support multiple instances of the FolioReader #140; Fixed bugs:

The user is forced to tap the cancel button one time to enable it and then there is no way you can enable the cancel button when the keyboard is dismissed, like Cancel, and you also want to dismiss when the user hits the clear (x) button. Shows how to use a keyboard accessory view. The application uses a single view controller. The view controller's view is covered by a text view. When you tap the text view, the view controller loads a nib file containing an accessory view that it assigns to the text view's inputAccessoryView property. The accessory view contains a button.

  • Can you briefly explain how you got TomSwift's suggestion to work? I couldn't get it working in my implementation.
  • question modified to show I got the class to serve as a TextField delegate.
  • I added the UISearchBar with Interface Builder and the X button shows up automatically after I've entered in a character into the Search Bar text field. I tried resigning both the searchBar (stored in the Controller class) and textfield. No luck
  • Okay, yeah I was being daft. I got that to work. Not sure why it's not dismissing, yet.
  • Oh it's the delay that seems to do it. With all of the hacking, I decided that trying to short circuit the SDK painful and went with adding the Cancel button. I'll have to do it the way the SDK intended.
  • Awesome sauce! A counter intuitive solution, but i'm nonetheless using it loud and proud. Thanks
  • Using GCD: dispatch_async(dispatch_get_main_queue(), ^(void){ [self.searchBar resignFirstResponder]; });
  • What happens when the user hits the delete button ? in that case the length of the searchText would be 0
  • @RodrigoGonzalez I honestly don't what happens on delete. I think in that case the search text should be cleared, and the keyboard disappear. Is this not what everyone wants?
  • I am confused though searchBar.endEditing(true) works on done/search button and cancel button but not on (X). Why ? anyone