iphone - 当没有单元格存在时单击 UITableView 的方法,以便键盘将关闭

标签 iphone ios objective-c

在屏幕上,用户可以单击文本字段来加载选择器以选择位置。然后,我根据此位置使用自定义单元格重新加载 TableView 中的所有元素。对于某些位置,可能没有要加载的内容,因此没有单元格。

当我有单元格并且用户从键盘上点击时,这部分代码会被很好地点击:

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.locationTextField resignFirstResponder];

    ...
}

我还有一段代码可以很好地处理不点击任何东西

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

但是当 tableview 没有单元格时,当用户单击 tableview 的空间时,这些都不会被触发。我可以设置其他东西来检测该区域的触摸吗?

最佳答案

您可以尝试使用 UITapGestureRecognizer 并将其添加到 TableView 中。 像这样:

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableViewTap:)];
[self.myTableView addGestureRecognizer:tapRecognizer];

然后:

-(void) tableViewTap:(UIGestureRecognizer*)recognizer 
{
    CGPoint tapLocation = [recognizer locationInView:self.myTableView];
    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:tapLocation];

    if (indexPath) //user tapped on a table cell
         recognizer.cancelsTouchesInView = NO;
    else //user tapped somewhere else on the table view
    {
        //your stuff here
    }
}

关于iphone - 当没有单元格存在时单击 UITableView 的方法,以便键盘将关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17989046/

相关文章:

iphone - 更改当前 iphone 应用程序的区域设置(NSBundle 的自定义区域设置?)

iphone - 阅读和EAGAIN

iphone - 如何使用数据包嗅探器确定应用程序是否使用 HTTP Live Streaming?

ios - 如果用户单击 Iphone 上的按钮,则从服务器下载并安装 IPA

ios - ios13 SKStoreProductViewController全屏

objective-c - 我应该如何在 Objective C 中找到过去的日期?

iphone - 继续添加到 NSMutableArray

iphone - 实时格式化美元金额

ios - HealthKit iTunes Connect 授权错误

objective-c - iOS - 防止 iPhone 配置文件被删除或检查它是否已安装