UILabel动画编号更改

时间:2011-10-17 19:52:16

标签: iphone objective-c ios cocoa-touch

我有一个显示用户分数的UILabel。并且评分会不时变化,是否有办法对此更改进行动画处理,以便将此数字从其当前值缓慢增加到其结果值? 像http://josheinstein.com/blog/index.php/2010/02/silverlight-animated-turbotax-number-display/这样的东西,但是对于objective-c。

2 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:4)

AUIAnimatedText已经满足您的要求。这是UILabel的替代品,具有触及文本动画的可能性,