2011-10-17 65 views
8

我有一个显示用户分数的UILabel。并且分数会不时变化,是否有办法让这个变化动起来,以便将这个数字从当前值慢慢增加到结果值? 类似于http://josheinstein.com/blog/index.php/2010/02/silverlight-animated-turbotax-number-display/,但是用于objective-c。UILabel动画数字变化

+0

我发现可能有助于回答 http://stackoverflow.com/questions/3073520/setting-new-text-to-uilabel-and-animation **首先看* * – wczekalski

+1

是的,我看到了,不是我想要的动画。 – Drabuna

回答

18

使用CADisplayLink可以在一段时间内更改UILabel的自定义子类的文本属性。你可能会想要使用NSNumberFormatter来获得更漂亮的输出。

// Create instance variables/properties for: `from`, `to`, and `startTime` (also include the QuartzCore framework in your project) 

- (void)animateFrom:(NSNumber *)aFrom toNumber:(NSNumber *)aTo { 
    self.from = aFrom; // or from = [aFrom retain] if your not using @properties 
    self.to = aTo;  // ditto 

    self.text = [from stringValue]; 

    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(animateNumber:)]; 

    startTime = CACurrentMediaTime(); 
    [link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; 
} 

- (void)animateNumber:(CADisplayLink *)link { 
    static float DURATION = 1.0; 
    float dt = ([link timestamp] - startTime)/DURATION; 
    if (dt >= 1.0) { 
     self.text = [to stringValue]; 
     [link removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; 
     return; 
    } 

    float current = ([to floatValue] - [from floatValue]) * dt + [from floatValue]; 
    self.text = [NSString stringWithFormat:@"%i", (long)current]; 
} 
+3

请注意,如果您确实使用了“NSNumberFormatter”,请创建其中一个并将其重用于使用相同格式的每个格式化作业。创建一个新的'NSNumberFormatter'非常昂贵,但重新使用现有的便宜。 –

+0

我一直在获取EXC_BAD_ACESS的 'float current =([to floatValue] - [from floatValue])* dt + [from floatValue]'; – Drabuna

+0

你是否使用'from'和'to'变量的属性?它是否设置为“保留”?如果你不使用属性,那么''from = [aFrom retain]' –

4

AUIAnimatedText有你所要求的。这是UILabel的替代方案,具有覆盖文字动画的可能性,