Search code examples
iosswiftuitableviewuiscrollviewuipangesturerecognizer

make pan gesture recognizer only respond when swiping down AND at the top of a tableview


I am trying to dismiss the current viewcontroller when the user swipes down at the top of the tableView. Since the tableview takes up the whole screen, my gesture and the tableView's gesture conflicts.

I thought about making my UIPanGestureRecognizer only respond if the user has not scrolled the tableview (tableView.contentOffset.y == 0.0) and the direction of the swipe is downwards. However, I have not succeeded implementing this.

This is my code:

var tableGesture: UIPanGestureRecognizer?
var oPosition: CGPoint?
var currentPosition: CGPoint?
@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    table.delegate = self
    table.dataSource = self

    tableGesture = UIPanGestureRecognizer(target: self, action: #selector(tableGesture(_:)))
    table.addGestureRecognizer(tableGesture!)
}

override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    let translation = tableGesture?.translation(in: table)
    return translation!.y > 0 && table.contentOffset.y == 0.0
}

I have looked around at similar questions but none of the answers worked for me.


Solution

  • The easiest way to do this is add another clear view on top of your tableView and add a pan gesture recognizer to this view. It can be quite short (I tried 20 points and that works fine). You can override scrollViewDidScroll and set isHidden to true only when contentOffset.y <= 0. The invisible view will now detect pans that start int he top 20 points of the tableview only when you are at the top of the tableView.