在滚动UIScrollView期间,UILabel更新停止

bra*_*dev 33 iphone objective-c uiscrollview uiviewcontroller ios

我有一个带有imageView的scrollView.这scrollView是superView的一个子视图,而imageView是一个子视图scrollView.我还有一个标签(在超级视图级别),每隔毫秒从NSTimer接收其text属性的更新值.

问题是:在滚动期间,标签停止显示更新.滚动结束时,标签上的更新将重新开始.更新重启时,它们是正确的; 这意味着label.text值按预期更新,但在滚动时,更新显示在某处覆盖. 无论滚动与否,我都希望在标签上显示更新.

以下是标签更新的实现方式:

- (void)startElapsedTimeTimer {

     [self setStartTime:CFAbsoluteTimeGetCurrent()];
     NSTimer *elapsedTimeTimer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(updateElapsedTimeLabel) repeats:YES];
}

- (void)updateElapsedTimeLabel {

    CFTimeInterval currentTime = CFAbsoluteTimeGetCurrent();
    float theTime = currentTime - startTime;

    elapsedTimeLabel.text = [NSString stringWithFormat:@"%1.2f sec.", theTime];
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

ser*_*gio 75

最近,我有同样的问题,在这里找到了解决办法:我的自定义UI元素....

简而言之:当您的UIScrollView滚动时,NSTimer不会更新,因为运行循环以不同的模式运行(NSRunLoopCommonModes,用于跟踪事件的模式).

解决方案是在创建后立即将计时器添加到NSRunLoopModes:

NSTimer *elapsedTimeTimer = [NSTimer scheduledTimerWithTimeInterval:0.001 
                                                             target:self 
                                                           selector:@selector(updateElapsedTimeLabel) 
                                                           userInfo:nil 
                                                            repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:elapsedTimeTimer 
                             forMode:NSRunLoopCommonModes];
Run Code Online (Sandbox Code Playgroud)

(代码来自上面链接的帖子).

  • 我使用与OP相同的电话.使用`timerWithTimeInterval:target:selector:userInfo:repeats`更为正确,因为我们要将计时器添加到运行循环中,所以不需要调度的`scheduled`版本. (2认同)
  • 这就是我在滚动时没有调用NSURLConnection委托方法的原因; 我需要使用NSURLConnection的`scheduleInRunLoop:forMode:`方法.所以+1指向我正确的方向. (2认同)

pro*_*ace 7

sergio在Swift 5中解决方案:

timer = Timer(timeInterval: 1, repeats: true) { [weak self] _ in
    self?.updateTimeLabel()
}
RunLoop.current.add(timer, forMode: .common)
Run Code Online (Sandbox Code Playgroud)