iOS - UILongPressGestureRecognizer

iOS - UILongPressGestureRecognizer

在我的应用程序中,我希望 UILongPressGestureRecognizer 每秒发送连续的消息,直到释放按钮。不幸的是,没有像 "continuous" 这样的状态,所以我需要使用 "began" 和 "ended" 来控制我的消息。这是我到目前为止的代码,我在终端上得到了两个日志,但是 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;
    }
}

有人可以帮忙吗?

使用计时器(或可能隐藏计时器的 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");
}