UILabel animating number change

前端 未结 2 1722
半阙折子戏
半阙折子戏 2021-01-31 23:26

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 valu

相关标签:
2条回答
  • 2021-01-31 23:53

    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];
    }
    
    0 讨论(0)
  • 2021-02-01 00:13

    AUIAnimatedText has all you was asking for. That is replacement for UILabel with reach text animating possibilities ,

    0 讨论(0)
提交回复
热议问题