OGeek|极客世界-中国程序员成长平台

标题: ios - 检测对 UITableView 空白区域的点击 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:39
标题: ios - 检测对 UITableView 空白区域的点击

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

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

这就是它的样子。

enter image description here

当前实现: 我正在使用 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)dismissKeyboardUITapGestureRecognizer *)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 空白区域的点击吗?



Best Answer-推荐答案


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

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

关于ios - 检测对 UITableView 空白区域的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33528580/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4