Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add UIPanGestureRecognizer to UIScrollView subviews

I am adding subviews to a UIScrollView and then I add UIPanGestureRecognizer to these subviews. Everything works fine but now after adding UIPanGestureRecognizer to subviews of the scroll view, scrolling is not possible.

What can be the possible solution to this issue?

like image 932
Shubham Avatar asked Feb 04 '12 12:02

Shubham


3 Answers

Swift 4

Conform the view controller to the UIGestureRecognizerDelegate...

SomeViewController: UIViewController, UIGestureRecognizerDelegate {
    ...
}

...set the view controller as the custom pan gesture recognizer's delegate...

customPanGestureRecognizer.delegate = self

...and using the simultaneous delegate, allow the custom panner and the scroll view's (or table view's) panner to operate simultaneously...

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {

    if otherGestureRecognizer == scrollView.panGestureRecognizer { // or tableView.panGestureRecognizer
        return true
    } else {
        return false
    }

}

There are two other methods that ask the delegate if a gesture recognizer should require another gesture recognizer to fail or if a gesture recognizer should be required to fail by another gesture recognizer. You will likely need further optimization beyond this but this is the starting point.

like image 57
liquid LFG UKRAINE Avatar answered Nov 15 '22 21:11

liquid LFG UKRAINE


The problem is that the pan gesture recognizer is what is used in the scroll view to control scrolling. Your gesture recogniser is taking priority and disabling the scroll views

If you want to always be able to scroll you can set your gesture recogniser to require the scroll views one to fail before it will work:

[self.myCustomPanRecognizer requireGestureRecognizerToFail:self.scrollView.panGestureRecognizer]; 

Edit: as Bastian pointed out in the comments, the reference to pan guesture is only in iOS 5, prior to this, check the array of gesture recognisers and find the one of type UIPanGestureRecognizer

if you want both to work you may need to do something to separate your recogniser from the scroll views, e.g. make the user tap and hold before your custom recogniser will be recognised.

there is also a delegate method which will allow both recognisers to work together, but I'm not sure how well this works when both are the same type

like image 22
wattson12 Avatar answered Nov 17 '22 07:11

wattson12


If you want to use both simultaneus you can use

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer

from the delegate, but that is probably not what you want ;)

like image 10
Bastian Avatar answered Nov 17 '22 08:11

Bastian