【发布时间】: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