iOS 金额余额从0跳动显示的动画

iOS 金额跳动显示动画

我们平时在做关于金额显示时,一个冷冰冰的金额放在label上总是感觉缺一点什么。我们可以对显示的金额做一个从0增长跳动到相应数字的动画效果。我们来看看实现过程

主页面

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) UILabel *moneyLabel;
@property (nonatomic, strong) NSTimer *balanceLabelAnimationTimer;

@end

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.moneyLabel];

    [self setNumberTextOfLabel:self.moneyLabel WithAnimationForValueContent:50000.00];
}

- (UILabel *)moneyLabel
{
    if (!_moneyLabel) {
        _moneyLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 300, 200, 80)];
        _moneyLabel.textColor = [UIColor whiteColor];
        _moneyLabel.textAlignment = NSTextAlignmentCenter;
        _moneyLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:50];
    }
    return _moneyLabel;
}

#pragma mark --- 余额显示的动画----
- (void)setNumberTextOfLabel:(UILabel *)label WithAnimationForValueContent:(CGFloat)value
{
    CGFloat lastValue = [label.text floatValue];
    CGFloat delta = value - lastValue;
    if (delta == 0) {
        return;
    }

    if (delta > 0) {

        CGFloat ratio = value / 30.0;

        NSDictionary *userInfo = @{@"label" : label,
                                   @"value" : @(value),
                                   @"ratio" : @(ratio)
                                   };
        _balanceLabelAnimationTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(setupLabel:) userInfo:userInfo repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_balanceLabelAnimationTimer forMode:NSRunLoopCommonModes];
    }
}

- (void)setupLabel:(NSTimer *)timer
{
    NSDictionary *userInfo = timer.userInfo;
    UILabel *label = userInfo[@"label"];
    CGFloat value = [userInfo[@"value"] floatValue];
    CGFloat ratio = [userInfo[@"ratio"] floatValue];

    static int flag = 1;
    CGFloat lastValue = [label.text floatValue];
    CGFloat randomDelta = (arc4random_uniform(2) + 1) * ratio;
    CGFloat resValue = lastValue + randomDelta;

    if ((resValue >= value) || (flag == 50)) {
        label.text = [NSString stringWithFormat:@"¥%.2f", value];
        flag = 1;
        [timer invalidate];
        timer = nil;
        return;
    } else {
        label.text = [NSString stringWithFormat:@"%.2f", resValue];
    }
    flag++;
}
运用RunLoop和NSTimer对显示动画进行相应跳动,原理就是把输入的金额经过取随机数,在label上进行显示。跳动次数可以在value / 30.0那里进行改动,跳动频率可以在[NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(setupLabel:) userInfo:userInfo repeats:YES];0.02这里进行动画频率的改动。

你可能感兴趣的:(ios-金额跳动动画)