Reputation:
As a shortcut (by no means necessary) I have a UIPanGestureRecognizer on my view to allow the user to slide his/her finger up and down to set a value quickly, but I'm having trouble implementing this fully.
I want to have it so a certain distance panned up or down increases or decreases the value proportionately.
I tried to use translationInView:
, but it only seems to be updating a few times unless I pan very slowly, unless I'm using it wrong.
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint velocity = [recognizer velocityInView:recognizer.view];
NSNumber *WPM = [[NSUserDefaults standardUserDefaults] objectForKey:@"WPM"];
// If user is panning upward
if (velocity.y < 0) {
CGPoint translation = [recognizer translationInView:recognizer.view];
if (fmodf(translation.y, 10) == 0) {
WPM = @([WPM intValue] + 5);
[[NSUserDefaults standardUserDefaults] setObject:WPM forKey:@"WPM"];
NSLog(@"%@", WPM);
}
}
// If user is panning downward
else if (velocity.y > 0) {
CGPoint translation = [recognizer translationInView:recognizer.view];
if (fmodf(translation.y, 10) == 0) {
WPM = @([WPM intValue] - 5);
[[NSUserDefaults standardUserDefaults] setObject:WPM forKey:@"WPM"];
NSLog(@"%@", WPM);
}
}
}
If I drag slowly, the variable's value will climb relatively fast, but if I slide my finger up the screen very quickly, it barely adjusts the value at all. I want the exact opposite of this; slow movement allows fine control, while a fast motion allows quicker change.
How exactly would I go about implementing this? It's not working very well as is.
Upvotes: 3
Views: 4417
Reputation: 31745
The trouble with your algorithm is that it only registers change when it happens to be an exact multiple of ten. As you pan faster, each registered translation.y may change by >1, so not all exact multiples register, resulting in fewer increments, not more.
You want to register change whenever it exceeds ten, then reset to zero.
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
NSNumber *WPM = [[NSUserDefaults standardUserDefaults] objectForKey:@"WPM"];
CGPoint translation = [recognizer translationInView:recognizer.view];
if (translation.y<-10 || translation.y>10) {
int sign = (translation.y>0)?-1:1;
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
WPM = @([WPM intValue] + sign*5);
[[NSUserDefaults standardUserDefaults] setObject:WPM forKey:@"WPM"];
NSLog(@"%@", WPM);
}
}
Upvotes: 3