简体   繁体   English

触摸屏幕时如何隐藏键盘(搜索栏)

[英]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. 谢谢。

Try This 试试这个

in your .h file add UISearchBar 在.h文件中添加UISearchBar

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

in your .m file 在.m文件中

- (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. 您可以添加UITapGestureRecognizer来关闭键盘。

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

- (void) dismissKeyboard {
     [self.view endEditing:YES];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM