问题
I have a gesture recognizer on a UIScrollView, however it hardly ever gets called as the UIScrollView eats all the gestures.
I partially got around this issue with this line: [scrollView.panGestureRecognizer requireGestureRecognizerToFail:rightSwipe]; however, this line results in my recognizer always being accepted (the desired behavior) and the scroll view not scrolling.
That is, when you scroll, the recognizer is accepted but the view doesn't scroll.
How can I get around this, or is there an alternate solution?
Thanks!
回答1:
Make a subclass of UIScrollView. Add this method in your new subclass
- (BOOL)gestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UISwipeGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
Make your scrollView class to your new scrollview subclass.
回答2:
Don't forget to assign proper delegation to your gesture recognizer mechanism:
So, for example:
Set a .up direction gesture recognizer
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:)))
swipeUp.direction = .up
swipeUp.delegate = self // set delegate
self.addGestureRecognizer(swipeUp)
Set a .down direction gesture recognizer
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(self.handleGesture(gesture:)))
swipeDown.direction = .down
swipeDown.delegate = self // set delegate
self.addGestureRecognizer(swipeDown)
Also don't forget to conform to delegation:
YourViewController: UIGestureRecognizerDelegate
Set simultaneous recognition:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
Then move on to your logic...
Hope it helps!
回答3:
The way that works for me is subclass UIScrollView and conform to UIGestureRecognizerDelegate in that subclass. Then call the method.
class ATScrollView: UIScrollView, UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
回答4:
Swift method,
Need to add UIGestureRecognizerDelegate to your class:
class ViewController: UIViewController, UIGestureRecognizerDelegate {
Need to set its delegate to self:
override func viewDidLoad() {
super.viewDidLoad()
var scrollView = UIScrollView(frame: self.view.frame)
scrollView.delegate = self
}
Add this part in your class methods to active simultaneous gestures:
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
来源:https://stackoverflow.com/questions/23841045/how-to-have-a-uiscrollview-scroll-and-have-a-gesture-recognizer