将 tapGesture 添加到 tableView 则无法执行 tableView(_ tableView: UITableView, didSelectRowAt indexPath: Index

Posted

技术标签:

【中文标题】将 tapGesture 添加到 tableView 则无法执行 tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 方法【英文标题】:Add tapGesture to tableView then can not perform tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) method 【发布时间】:2016-12-22 09:41:36 【问题描述】:

众所周知,我们使用下面的代码可以endEditingsearchBar的firstResponder,但是如果有scrollView或者tableView,效果就不一样了。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
    super.touchesBegan(touches, with: event)

    self.view.endEditing(true)

我将tapGesture 添加到tableView,所以我可以endEditing searchBar 的firstResponder。

但是将tapGesture添加到我的tableView后,tableView的tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)函数就不再起作用了。

我该如何解决这个问题?


加法

我有用的代码如下:

let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapTableView))
self.tableView.addGestureRecognizer(tap)


func tapTableView() 

    self.searchBar.endEditing(true)

【问题讨论】:

除非您检查它正在触摸的视图,否则它将覆盖所有触摸,相反您可以考虑在内置的 tableview 上使用 keyboardDismiss,例如 .interactive @SeanLintern88 你是什么意思在 tableView 上使用 kwyboardDismiss ? 【参考方案1】:

在视图上而不是在 tableView 上添加 tapGesture

let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapTableView))
self.view.addGestureRecognizer(tap)

【讨论】:

然后你把'self.searchBar.endEditing(true)'这个改成'self.view.endEditing(true)' 是同一个兄弟,这个评论没用。【参考方案2】:

改为在您的表格视图上添加

    tableView.keyboardDismissMode = .onDrag

您也可以将.onDrag 更改为.interactive。移除 Touches 开始了。

编辑:来自苹果文档

case none
    The keyboard does not get dismissed with a drag.
case onDrag
    The keyboard is dismissed when a drag begins.
case interactive
    The keyboard follows the dragging touch offscreen, and can be pulled upward again to cancel the dismiss.

【讨论】:

您能提供更详细的信息吗?我设置了tableView.keyboardDismissMode = .onDrag或者. interactive ,没有效果,是不是哪里出错了?

以上是关于将 tapGesture 添加到 tableView 则无法执行 tableView(_ tableView: UITableView, didSelectRowAt indexPath: Index的主要内容,如果未能解决你的问题,请参考以下文章

将 UITapGesture 添加到 UIScrollView

iOS TapGesture 不工作

swift自定义上下文菜单previewprovider不能点击里面的任何视图(使用tapgesture)

UITextField TapGesture 在 iOS 7.1 上没有响应

如何在 UIView 中为 UIImageView 添加 tapGesture

TapGestures 在自定义 TableViewCell 中不起作用