Search code examples
ioskeyboardhidesearchbar

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


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.


Solution

  • 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];
    }