Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel updating stops during scrolling UIScrollView

I have a scrollView with an imageView inside of it. The scrollView is a subView of the superView, and the imageView is a subView of the scrollView. I also have a label (at the super-view level) that receives updated values on its text property from a NSTimer every millisecond.

The problem is: During scrolling, the label stops to display the updates. When the scrolling is end, updates on the label restart. When updates restart they are correct; this means that label.text values are updated as expected, but while scrolling, updates display is overriden somewhere. I would like to display updates on the label regardless of scrolling or not.

Here is how the label updates are implemented:

- (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]; } 

Thanks for any help.

like image 871
brainondev Avatar asked Mar 21 '11 13:03

brainondev


2 Answers

I had recently the same trouble and found the solution here: My custom UI elements....

In short: while your UIScrollView is scrolling, the NSTimer is not updated because the run loops run in a different mode (NSRunLoopCommonModes, mode used for tracking events).

The solution is adding your timer to the NSRunLoopModes just after creation:

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

(The code comes from the post linked above).

like image 77
sergio Avatar answered Oct 07 '22 06:10

sergio


sergio's solution in Swift 5:

timer = Timer(timeInterval: 1, repeats: true) { [weak self] _ in     self?.updateTimeLabel() } RunLoop.current.add(timer, forMode: .common) 
like image 33
protspace Avatar answered Oct 07 '22 05:10

protspace