سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
   [yourTextField1 resignFirstResponder];
   [yourTextField2 resignFirstResponder];
   [yourTextField3 resignFirstResponder];
   [yourSearchBar resignFirstResponder];
   //etc
}

But probably you need to check where are you touching at since you don't want to hide the keyboard if you're touching on a text input or search box.

Try to use this one

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
  [self.view endEditing:YES];
}

You could add a UITapGestureRecognizer to dismiss your keyboard.

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

- (void) dismissKeyboard {
     [self.view endEditing:YES];
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top