Search code examples
ioscore-animationsynchronouscakeyframeanimation

How do I synchronize change in a UILabel text with a related animation?


I have an animation of a drinking glass filling up from empty to full, using CAKeyframeAnimation. The animation works perfectly fine.

I need to update a UILabel with the percentage corresponding to the fullness of the glass, i.e. it will read "0%" when the animation begins, and "100%" when it ends.

The keyframe animation runs for 5 seconds. I don't see a good way of updating this label. I can think of two options:

  1. starting another thread and running a polling-type loop that updates the text at the cost of processing power.
  2. break down the animation into 100 parts and use CABasicAnimation to update the text and then proceed with the next bit of glass animation.

Is there a better way to do this?

Thanks in advance


Solution

  • You can use either a NSTImer or dispatch_after() blocks to update the label at some scheduled interval:

    // assume an ivar "NSTimer *myTimer" and "int count", initially 0
    
    // fires 20 times, so update is 0.05
    myTimer = NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(updateLabel:) userInfo:nil repeats:YES
    
    - (void)updateLabel:(NSTimer *)timer
    {
      ++count;
      if(count >= 20) {
         [timer invalidate];
      }
      CGFloat percent += 0.05;
      myLabel.text = [NSString stringWithFormat:...
    }