Reputation: 129
In my app I want the UILongPressGestureRecognizer will send continuous messages every second until the button is released. Unfortunately there is no state like "continuous" so I need to use "began" and "ended" to control my messages. Here is my code I have so far, I get both logs on the terminal but the while loop is not stopping?
- (void)longPress:(UILongPressGestureRecognizer*)gesture {
BOOL loop = NO;
if (gesture.state == UIGestureRecognizerStateBegan) {
NSLog(@"Long press detected.");
loop = YES;
while (loop){
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
// here I want to do my stuff every second
}
} else if (gesture.state == UIGestureRecognizerStateEnded) {
NSLog(@"Long press Ended");
loop = NO;
}
}
Does anyone please can help?
Upvotes: 1
Views: 406
Reputation: 62676
Its a good suggestion to use a timer (or a performSelector:withDelay:
which probably conceals a timer) but, roughly:
@property(strong,nonatomic) NSTimer *timer;
- (void)longPress:(UILongPressGestureRecognizer*)gesture {
if (gesture.state == UIGestureRecognizerStateBegan) {
NSLog(@"started");
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(stillPressing:) userInfo:nil repeats:YES];
} else if (gesture.state == UIGestureRecognizerStateEnded) {
[self.timer invalidate];
self.timer = nil;
NSLog(@"ended");
}
}
- (void)stillPressing:(NSTimer *)timer {
NSLog(@"still pressing");
}
Upvotes: 1