Reputation: 29326
In order to show that a certain state is in progress, I'm "pulsing" the UILabel that corresponds to that state, fading it from white to dark grey repeatedly.
I'm accomplishing this with NSTimers as shown below:
- (void)pulseColorsOfLabel:(NSTimer *)timer {
_timer = timer;
UILabel *labelToPulse = timer.userInfo;
// Check pulseCycle to determine at what point in the color transition the label is
if (_pulseCycle == 0) {
[UIView transitionWithView:labelToPulse duration:0.75 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
labelToPulse.textColor = [UIColor darkGrayColor];
} completion:nil];
_pulseCycle = 1;
}
else if (_pulseCycle == 1) {
[UIView transitionWithView:labelToPulse duration:0.75 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
labelToPulse.textColor = [UIColor whiteColor];
} completion:nil];
_pulseCycle = 0;
}
}
And I use an NSTimer call to make that method fire every 0.75 seconds:
[NSTimer scheduledTimerWithTimeInterval:0.75 target:self selector:@selector(pulseColorsOfLabel:) userInfo:self.stateLabel repeats:YES];
And as the application goes through the various states, it marks the just completed state label green, invalidates the timer, and then changes the next state label to be pulsing (there's multiple states the app has to go through) with another NSTimer call. Basically a method is called as a delegate when the state changes, then the state is checked with a switch
statement and the appropriate colors and pulsings are set.
Problem is, sometimes in the process of all the state labels turning green, some will disappear completely (as I assume they get stuck in the faded to white state against the white background) and sometimes they stay dark, or sometimes they pulse very sporadically.
I know this is an issue with the timers, as if I get less fancy and just make it change the state label to orange when in progress instead of pulsing, it works beautifully every time.
Any ideas what I could be doing here to make sure all the timer calls work well in conjunction with one another, and don't mess up the coloring of the labels?
Upvotes: 0
Views: 349
Reputation: 5655
I noticed in your code that _timer
is assigned when the timer fires, which means that if the current timer hadn't fired at least once yet, you wouldn't be able to cancel it. Try invalidating and assigning the timer when you schedule it:
[_timer invalidate];
_timer = [NSTimer scheduledTimerWithTimeInterval:0.75 target:self selector:@selector(pulseColorsOfLabel:) userInfo:self.stateLabel repeats:YES];
If that doesn't work, some of your animations may be getting interrupted. Try removing the old animation before adding a new one:
UILabel *labelToPulse = timer.userInfo;
[labelToPulse.layer removeAllAnimations];
Upvotes: 1