【问题标题】:Detect tap on empty area of UITableView检测对 UITableView 空白区域的点击
【发布时间】:2015-11-04 17:44:42
【问题描述】:

我有一个 UIViewController,它下面有一个 UITextFiled 和一个 UITableView。我在 UITableView 上使用 UITextField 作为搜索框。

当我在 UITextField 内点击时,会出现我希望在点击 UITableView 的任何区域时消失的虚拟键盘。当用户点击 UITableView 和 UITextField 以外的任何区域时,键盘也应该消失。如果键盘不可见并且用户点击了任何 UITableViewCell,那么我需要打开另一个 UIViewController。

这就是它的样子。

当前实施: 我正在使用 UITapGestureRecognizer 来检测点击位置。另外我正在使用 shouldReceiveTouch 来查找触摸是否在 UITableView 上。如果是,那么我返回 NO,这意味着我忽略了 UITableView 上的触摸。如果不是,那么我将返回 YES 并在 UITapGestureRecognizer 处理程序中通过调用来关闭键盘

    [self.searchTextField resignFirstResponder];

现在我面临的问题是:当我的 UITableView 没有足够的数据并且它只显示 1 或 2 个单元格时,在这种情况下,我希望在我点击时关闭键盘UITableView 的空白区域,但不会因为点击在 UITableView 上,并且 shouldReceiveTouch 将返回 NO 并忽略触摸。

注意 我首先实现 shouldReceiveTouch 的原因是我希望在用户点击任何单元格时自动调用 didSelectRowAtIndexPath 函数。这只有在我忽略 UITableView 上的 Tapgesture 时才有可能。

我尝试了另一种方法,其中我没有实现 shouldReceiveTouch 并且在每次点击时我都调用 UITapGestureRecognizer 处理程序并检测触摸是否在 UITableView 内。在那种情况下,我没有得到被点击的正确行索引。这就是我实现它的方式:

-(void)dismissKeyboard:(UITapGestureRecognizer *)tap
{
     if([self.searchTextField isFirstResponder])
     {
         [self.searchTextField resignFirstResponder];
         return;
     }

     CGPoint location = [tap locationInView:self.view];

     if(touchedOutsideUITableView)
     return;

     NSIndexPath *path = [self.lotsTableView indexPathForRowAtPoint:location];

     if(path)
     {
     // user taps on existing row
     [self tableView:self.lotsTableView didSelectRowAtIndexPath:path];
     }
     else
     {
     // handle tap on empty area of UITableView
     }
}

谁能告诉我如何在我当前的实现中检测 UITableView 空白区域的点击?

【问题讨论】:

  • 你为什么不使用UISearchController
  • 它将如何帮助我解决当前的问题?
  • 它将为您的表格提供预期的搜索界面,并且可以防止您面临的问题甚至存在。

标签: ios objective-c iphone uitableview


【解决方案1】:

如果只保留您的 UITapGestureRecognizer 而将 cancelsTouchesInView 设置为 NO 会怎样?默认是YES

这样,当您点击任何单元格时,您的 didSelectRowAtIndexPath 方法仍然会被调用。

【讨论】:

    【解决方案2】:

    我认为只实现textFieldShouldBeginEditing 会更容易,当它触发时将UITapGestureRecognizer 添加到您的tableView。然后在用户停止编辑文本字段后立即删除UITapGestureRecognizer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-20
      • 2012-06-21
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多