SWIFT4:如何让两个点击手势识别器协同工作

SWIFT4: How to have two tap gestureRecognizers work together

注意:我的手势识别器没有什么不同,并且在不同的视图控制器中。

TLDR: How can I do to have both my tap gesture recognisers to work?

我从一些容器视图中创建了一个 side menu,并向其中添加了一个手势识别器,允许我在点击时关闭它。然后我创建了另一个 ViewController ,其中有一些文本字段。因为我希望键盘在点击时关闭,所以我什至添加了一个手势识别器,允许我在点击视图时隐藏键盘。现在我注意到隐藏键盘的手势不会让我的侧边菜单在点击时隐藏:

侧边菜单视图控制器

  @IBOutlet weak var bigContainer: UIView!
  @IBOutlet weak var sideMenuConstraint: NSLayoutConstraint!

    var sideMenuOpen = false
    var gesture : UITapGestureRecognizer?


    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(toggleSideMenu), name: NSNotification.Name("ToggleSideMenu"), object: nil)


       gesture = UITapGestureRecognizer(target: self, action: #selector(ContainerViewController.toggleSideMenu))


    }


    @objc func toggleSideMenu() {
        if sideMenuOpen {
            sideMenuOpen = false
            sideMenuConstraint.constant = -240
        self.bigContainer.removeGestureRecognizer(gesture!)
        } else {
            sideMenuOpen = true
           sideMenuConstraint.constant = 0
         self.bigContainer.addGestureRecognizer(gesture!)

        }
    }

主视图视图控制器

@IBOutlet weak var textField: UITextField!
 @IBOutlet weak var menuOutlet: UIButton!
 override func viewDidLoad() {
        super.viewDidLoad()
  let endEditingTapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
        endEditingTapGesture.cancelsTouchesInView = false
        view.addGestureRecognizer(endEditingTapGesture)
}
 @IBAction func toggleSideMenu(_ sender: Any) {
        print("Toggle side menu")
        NotificationCenter.default.post(name: NSNotification.Name("ToggleSideMenu"), object: nil)

    }
}

我尝试删除点击手势以隐藏 toggleSideMenu 按钮中的键盘,但没有成功。

在你的MAIN VIEW CONTROLLER中替换为以下代码:

    var endEditingTapGesture:UIGestureRecognizer!

override func viewDidLoad() {
    super.viewDidLoad()
    endEditingTapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:)))
    endEditingTapGesture.cancelsTouchesInView = false


    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notication:)), name: UIResponder.keyboardWillHideNotification, object: nil) //Add keyboard notification
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notication:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
@IBAction func toggleSideMenu(_ sender: Any) {
    print("Toggle side menu")
    NotificationCenter.default.post(name: NSNotification.Name("ToggleSideMenu"), object: nil)

}

//Keyboard method
@objc func keyboardWillHide(notication:Notification) {
    view.removeGestureRecognizer(endEditingTapGesture)
}

@objc func keyboardWillShow(notication:Notification) {
    view.addGestureRecognizer(endEditingTapGesture)
}