在我的应用程序中,我希望UILongPressGestureRecognizer每秒都会发送连续的消息,直到按钮被释放。不幸的是,没有像#34;连续"所以我需要使用"开始"并且"结束"控制我的消息。这是我到目前为止的代码,我在终端上都有两个日志但是while循环没有停止?
- (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;
}
}
有人可以帮忙吗?
答案 0 :(得分:1)
这是一个很好的建议,使用计时器(或performSelector:withDelay:
可能隐藏计时器),但大致:
@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");
}