UILabel数字变化动画

8

我发现这可能很有帮助https://dev59.com/_nA75IYBdhLWcg3w182G首先寻找答案 - wczekalski
1
是的,我看到了,这不是我正在寻找的那种动画。 - Drabuna
2个回答

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非常昂贵,但是重复使用现有的则很便宜。 - Lily Ballard
我一直在这个地方遇到EXC_BAD_ACCESS错误: float current = ([to floatValue] - [from floatValue]) * dt + [from floatValue]; - Drabuna
你是否在fromto变量中使用了属性?并且它们的设置为retain吗?如果你没有使用属性,请使用from = [aFrom retain] - Jason Harwig
在模拟器上运行得很好,但在 iPhone 上却不行。它在“从”和“到”之间显示一个数字,然后是“到”数字。似乎有点卡顿。有什么建议吗? - Drabuna
在模拟器和设备上都运行得非常好。太棒了Jason。你真棒! - JAHelia

4

AUIAnimatedText 就是你所需要的一切。它是一个可以替代UILabel并具有丰富文本动画功能的组件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接