【问题标题】:iOS dismisskeyboard on tap outside of the searchbariOS 在搜索栏外点击时关闭键盘
【发布时间】:2014-09-23 00:55:44
【问题描述】:

我有一个标签栏应用程序,在其中一个标签中我有一个搜索栏。

正如预期的那样,当用户聚焦搜索栏时,键盘会出现,但在标签栏上方。因此,当用户在搜索栏外点击时,我想将其关闭。

我使用以下代码:

在viewDidLoad

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                  initWithTarget:self action:@selector(handleTap:)];
[tapRecognizer setCancelsTouchesInView:NO];
[self.tableView addGestureRecognizer:tapRecognizer];

还有handleTap

- (void) handleTap: (UITapGestureRecognizer *)recognizer
{
    [self.theSearchBar resignFirstResponder];
}

问题是即使我点击搜索选项,键盘也会被关闭,这不是我想要的行为。我希望仅在点击位于搜索栏之外时关闭键盘。

我还尝试在handleTap 中使用recognizer.view 来识别何时执行点击,但在这种情况下只有一个视图并且无法识别点击位置。

所以问题是:如何在用户点击搜索栏外时关闭键盘,而不是在用户点击搜索选项按钮时关闭键盘。

【问题讨论】:

  • 你在tableview中使用了sear bar,你的编码很好,它在segment中工作也不能在tableview中正常工作
  • 将 Interface Builder 中 View 对象的类标识(正如我在 Xcode 4 中所理解的那样控制)从 UIView 更改为 UIControl 并在事件列表中使用文件所有者连接 TouchDown 方法并检查方法 backgroundTap。 - (IBAction)backgroundTouched:(id)sender { [self.view endEditing:YES]; }
  • 在handleTap: 中检查if([recognizer.view isEqual:self.tableView]){ } 对您不起作用?
  • @SuryakantSharma 我已经尝试过了,正如我在问题中提到的那样,似乎只有一个视图存在,因此点击选项按钮或背景会给出相同的结果。
  • 你在UITableView上添加了搜索栏和标签栏吗?

标签: ios keyboard uisearchbar dismiss


【解决方案1】:

试试这个

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

其他选择

将Cancel Button 添加到UI search bar

 - (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar{
    [searchBar resignFirstResponder];
 }

【讨论】:

  • +1 使用取消按钮的想法是个好主意。现在对于触摸事件,现在我无法触发它。每当我点击它时,它都不会被调用。
  • 我忘记添加用户交互已启用。我不明白为什么不调用 touchesBegan。
  • touch started 在普通视图中运行良好,但您在 superview (tableview) 中调用了 s y 无法正常运行
猜你喜欢
  • 2017-10-25
  • 2020-02-14
  • 2019-01-31
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
相关资源
最近更新 更多