How to hide the keyboard when touching screen (search bar)

Rick picture Rick · Jun 6, 2013 · Viewed 16.6k times · Source

The keyboard hides when I click search or when I click on cancel. But I want also that the keyboard hides when I click somewhere on the screen. I found several tutorials for the textfield, but we are using the search bar.

Can someone tell me how to do this?

Thanks.

Answer

iMubarak picture iMubarak · Jun 6, 2013

Try This

in your .h file add UISearchBar

@property (strong, nonatomic) IBOutlet UISearchBar *searchBar; 

in your .m file

- (void)viewDidLoad
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];

    [self.view addGestureRecognizer:tap];
}


- (void) dismissKeyboard
{
    // add self
    [self.searchBar resignFirstResponder];
}