UILabel动画编号更改

Dra*_*una 8 iphone cocoa-touch objective-c ios

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

Jas*_*wig 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];
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您使用`NSNumberFormatter`,请创建其中一个并将其重复用于使用相同格式的每个格式化作业.创建一个新的`NSNumberFormatter`是相当昂贵的,但重新使用现有的便宜. (3认同)