Jack Li Jack Li - 2 months ago 21x
iOS Question

UITapGestureRecognizer with collapsible sidebar menu Swift

I am currently programming an app which contains a home screen view controller and a sidebar menu view which is instantiated upon loading the home screen and is opened when clicking a hamburger icon. I am trying to implement the feature that clicking outside of the menu while it's open closes the menu, and restores normal function to the home view, which was disabled upon opening the menu.
I've instantiated a

to detect when the user taps on the home view.

let tapRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(HomeViewController.handleTap(_:)))

And here's the implementation:

func handleTap(sender: UITapGestureRecognizer) {
if menu.isMenuOpen {
self.tableView.allowsSelection = false

However, tapping on the menu closes the menu just the same as tapping outside of the menu. Also, because the tap gesture recognizer only recognizes that specific tap, everything on the home screen is always disabled. I am running XCode 7.3 on iOS 9.3. Image:
Home view controller with menu open


You can implement UIGestureRecognizerDelegate and set tapRecognizer.delegate = self.

Then implement below method

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
    if (gestureRecognizer == tapRecognizer){
    let point = touch.locationInView(self.view)
        if CGRectContainsPoint(menuView.frame, point) == true {
            return false