问题
I have a method that I would like to call when a 2 finger pan gesture is recognized. I have it setup and working ok, but the problem is that there is only about 15 times I need the method to be called (it filters through images), and by the time I've panned about an inch, the method has been called a hundred times and the images went by so fast I didn't know what was going on.
What can I do to slow down my gesture recognizer?
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[panRecognizer setMinimumNumberOfTouches:2];
[panRecognizer setMaximumNumberOfTouches:2];
[panRecognizer setDelegate:self];
[self view] addGestureRecognizer:panRecognizer]];
回答1:
Presumably you're changing images every time you get a pan event. That's not very good. Instead you should ask the pan gesture recognizer for the drag distance (use -translationInView:
) and only change images once you've passed a specific threshold.
回答2:
I created a "responseCount" basically capturing every 4th or 5th (valid) gesture.
// within method that fires with each gesture:
CGPoint translatedPoint = [(UIPanGestureRecognizer*)panRecognizer translationInView:aView];
if(abs(translatedPoint.x) > 20 || abs(translatedPoint.y) > 20){
if(responseCount == 4){
// do animation/response
responseCount = 0;
} else {
responseCount += 1;
}
}
回答3:
Swift 4
@objc func panGestureHandler(_ gesture: UIPanGestureRecognizer) {
let theViewMinimumY = someValue
let translation = gesture.translation(in: gesture.view)
switch gesture.state {
case .began:
gesture.setTranslation(CGPoint.zero, in: gesture.view)
case .changed:
gesture.setTranslation(CGPoint.zero, in: gesture.view)
// if the view ever goes beyond a certain point
if theView.frame.origin.y < theViewMinimumY {
// only add a fraction of the gesture's translation (in this case 50%)
theView.center = CGPoint(x: theView.center.x, y: theView.center.y + (translation.y * 0.5))
} else {
theView.center = CGPoint(x: theView.center.x, y: theView.center.y + translation.y)
}
case .ended:
...
default:
break
}
}
来源:https://stackoverflow.com/questions/5174116/how-to-slow-down-the-speed-of-uipangesturerecognizer