滚动时不会调用NSTimer周期性任务

Fr4*_*cis 9 scroll nstimer ios

我有一个NSTimer

timer = [NSTimer scheduledTimerWithTimeInterval:1 
                                         target:self 
                                       selector:@selector(periodicTimer) 
                                       userInfo:nil 
                                        repeats:YES];
Run Code Online (Sandbox Code Playgroud)

哪个

- (void)periodicTimer
{
    NSLog(@"Bang!");
    if (timerStart != nil)
        [timerLabel setText:[[NSDate date] timeDifference:timerStart]];        
}
Run Code Online (Sandbox Code Playgroud)

问题是,在滚动tableview(或执行其他任务)时,标签不会更新,此外,"砰!" 没有出现,所以我认为该方法不会被调用.

我的问题是如何定期更新标签,即使用户正在玩app界面.

Jor*_*ers 25

您需要将计时器添加到UITrackingRunLoopMode,以确保您的计时器在滚动期间也会触发.

NSRunLoop *runloop = [NSRunLoop currentRunLoop];
NSTimer *timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(myTimerAction:) userInfo:nil repeats:YES];
[runloop addTimer:timer forMode:NSRunLoopCommonModes];
[runloop addTimer:timer forMode:UITrackingRunLoopMode];
Run Code Online (Sandbox Code Playgroud)

来自:https: //stackoverflow.com/a/1997018/474896

  • 仅供参考 - NSRunLoopCommonModes包含iOS 7中的UITrackRunLoopMode (6认同)