Search code examples
iosuitableviewswiftuigesturerecognizeruiswipegesturerecognizer

UISwipeGestureRecognizer Custom Action with UITableView


I'm trying to add a swipe gesture (left/right) in order to hide/show my side menu. I got it working perfectly on a UIView, however, I'm having trouble with an UITableView.

Here's my code to add my swipe gestures to my TableView:

// Add right swipe gesture recognizer

    let rightSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "toggleSideMenu")
    rightSwipeGestureRecognizer.direction =  UISwipeGestureRecognizerDirection.Right
    self.timelineTableView.addGestureRecognizer(rightSwipeGestureRecognizer)

    // Add left swipe gesture recognizer
    let leftSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "toggleSideMenu")
    leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left
    //sideMenuContainerView.addGestureRecognizer(rightSwipeGestureRecognizer)
    self.timelineTableView.addGestureRecognizer(leftSwipeGestureRecognizer)

Here's my selector method :

func toggleSideMenu() {
    println("ENTER SWIPE")
    toggleSideMenuView()
}

I've also done this :

func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
    return UITableViewCellEditingStyle.None
}

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return false
}

However, my selector menu "toggleSideMenu()" is never called when I swipe left or right.

P.S: I've also tried to add those swipe gesture on my UITableViewCell directly but it doesn't work as well.

Anyone has an idea? Thanks a lot for your time!


Solution

  • Thanks to Kirit Modi. Here's the solution to my problem:

    Add :

    leftSwipeGestureRecognizer.delegate = self    
    rightSwipeGestureRecognizer.delegate = self
    

    Then add the UIGestureRecognizerDelegate delegate method :

    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
        return true
    }