UILabel动画数量变化 [英] UILabel animating number change
问题描述
我有一个UILabel显示用户分数。并且分数随时间变化,有没有办法动画这个变化,缓慢增加这个数字从其当前值到结果值?
像 http://josheinstein.com/blog /index.php/2010/02/silverlight-animated-turbotax-number-display/ 但是对于目标c。
I've got an UILabel that displays users score. And score changes from time to time, is there a way to animate this change, to slowly increment this number from its current value to its result value? Something like http://josheinstein.com/blog/index.php/2010/02/silverlight-animated-turbotax-number-display/ but for objective-c.
推荐答案
使用CADisplayLink在一段时间内更改UILabel的自定义子类的文本属性。您可能想要使用 NSNumberFormatter
来创建更漂亮的输出。
Use a CADisplayLink to change the text property of custom subclass of UILabel over some period of time. You'll probably want to use a NSNumberFormatter
for prettier output.
// 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];
}
这篇关于UILabel动画数量变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!