使用cancelsTouchesInView = false的iOS addGestureRecognizer不适用于子视图按钮

时间:2018-02-10 14:12:46

标签: ios swift uigesturerecognizer

我用这种方式实现了带有UIGestureRecognizer的ViewController:

// Extension for GestureRecognizer
extension UIViewController {
    func addGestureRecognizer() {
        let singleTap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        singleTap.cancelsTouchesInView = false
        singleTap.numberOfTapsRequired = 1
        self.view.addGestureRecognizer(singleTap)
    }

    @objc func handleTap(_ recognizer: UITapGestureRecognizer) {
        self.view.endEditing(false)
    }
}

如您所见,默认情况下,cancelsTouchesInView设置为false。它与searchBar和textFields的主视图一起正常工作。键盘被关闭,触摸被转换为查看对象 - 按钮等。

但我添加的子视图与AlertView一样,有几个UITextFields和UIButtons。这是一个问题。当提出子视图并点击此子视图的任何按钮时 - gestureRecognizer会做出反应并且键盘会消失。但没有其他事情发生。所以我必须第二次按下按钮才能按下它。 enter image description here

我试图将UITapGestureRecognizer的目标从self更改为self.mySubViewName,如下所示:

    func addGestureRecognizer() {
        let singleTap = UITapGestureRecognizer(target: self.addingItemView, action: #selector(self.handleTap(_:)))
        singleTap.cancelsTouchesInView = false
        singleTap.numberOfTapsRequired = 1
        self.view.addGestureRecognizer(singleTap)
    }

    @objc func handleTap(_ recognizer: UITapGestureRecognizer) {
        self.view.endEditing(false)
    }

这样GestureRecognizer就可以正常使用子视图按钮,但无法使用主视图。我开始得到"无法识别的选择器被发送"例如,尝试关闭搜索栏的键盘时出错。我试图实现单独的函数addGestureRecognizerForSubView,但仍然得到"无法识别的选择器已发送..."错误。

还尝试添加此内容:

extension MenuTableViewController: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        return touch.view == self.addingItemView
    }
}

但没有任何改变。

我在这里检查了很多答案,但无法找到我的案例。有人可以提供建议吗?我可以分享我的ViewController类,但它太沉重,看起来很丑,用编程方式添加了子视图:)

1 个答案:

答案 0 :(得分:1)

在警报后面添加子视图,并将手势添加到self.view

    let singleTap = UITapGestureRecognizer(target: self.otherView, action: #selector(self.handleTap(_:)))
    singleTap.cancelsTouchesInView = false
    singleTap.numberOfTapsRequired = 1
    self.otherView.addGestureRecognizer(singleTap)

编辑:您建议将其添加到子视图中是正确的

    let singleTap = UITapGestureRecognizer(target: self.addingItemView, action: #selector(self.handleTap(_:)))
    singleTap.cancelsTouchesInView = false
    singleTap.numberOfTapsRequired = 1
    self.view.addGestureRecognizer(singleTap)

但是你仍然将手势添加到self.view

      self.view.addGestureRecognizer(singleTap)

更改为

      self.addingItemView.addGestureRecognizer(singleTap)