【问题标题】:How to hide the keyboard when touching screen (search bar)触摸屏时如何隐藏键盘(搜索栏)
【发布时间】:2013-06-02 03:14:54
【问题描述】:

当我单击搜索或单击取消时,键盘会隐藏。 但我还希望当我单击屏幕上的某个位置时键盘会隐藏起来。 我找到了几个关于文本字段的教程,但我们正在使用搜索栏。

谁能告诉我怎么做?

谢谢。

【问题讨论】:

  • 你试过 Jensen2k 的这个答案了吗:stackoverflow.com/questions/5306240/…
  • 感谢您的回复。是的,我也试过那个。问题是我也没有连接键盘的文本字段。搜索栏调用键盘,因此我必须使用搜索栏将其退出。你知道另一种解决方案吗?还是谢谢!

标签: ios keyboard hide searchbar


【解决方案1】:

试试这个

在你的 .h 文件中添加 UISearchBar

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

在您的 .m 文件中

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

    [self.view addGestureRecognizer:tap];
}


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

【讨论】:

  • 试过第一部分没有给出任何错误,第二部分又说:'Unkown receiver 'searchBar';你是说 UISearchBar 吗?谢谢您的帮助。我认为这很接近。
  • 是的,我的意思是 UISearchBar。在您的界面 h 文件中定义您的 UISearchBar IBOutLet。
  • 是的,我忘了输入:@synthesize searchBar;在我的 .m 文件中。现在它起作用了。谢谢:D
  • 如果它解决了,你可以选择这个作为答案。这将有助于其他人找到答案。谢谢。
【解决方案2】:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
   [yourTextField1 resignFirstResponder];
   [yourTextField2 resignFirstResponder];
   [yourTextField3 resignFirstResponder];
   [yourSearchBar resignFirstResponder];
   //etc
}

但您可能需要检查您触摸的位置,因为如果您触摸的是文本输入或搜索框,您不想隐藏键盘。

【讨论】:

  • 也试过几次。我收到以下错误:Unkown receiver 'searchBar' did you mean UIDearchBar?
【解决方案3】:

尝试使用这个

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

【讨论】:

  • 我没有收到任何错误,但它也不起作用。什么都没发生。还是谢谢!
  • 如果您在视图内使用滚动视图,那么它将不起作用,否则它将起作用。
【解决方案4】:

您可以添加 UITapGestureRecognizer 来关闭您的键盘。

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

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

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 2011-03-11
    相关资源
    最近更新 更多