文字滚动效果实现

最近在项目中有个需求是要将金额数字以滚动增加的方式展示出来.效果类似于支付宝余额的显示样子
代码如下:

//创建
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 100, 300, 80)];
    self.moneyLabel.backgroundColor = [UIColor cyanColor];
    self.moneyLabel.textColor = [UIColor redColor];
    self.moneyLabel.textAlignment = NSTextAlignmentRight;
    self.moneyLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:50];
    self.moneyLabel.text = @"0.00";
    [self.view addSubview:self.moneyLabel];
    
}
//点击修改数字
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self setNumberTextOfLabel:self.moneyLabel WithAnimationForValueContent:1000000000.00];
}

//具体实现

//实现方法
- (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 / 60.0;
        
        NSDictionary *userInfo = @{@"label" : label,
                                   @"value" : @(value),
                                   @"ratio" : @(ratio)
                                   };
       [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(setupLabel:) userInfo:userInfo repeats:YES];
    }
}




- (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++;
    
}

实现效果如下

文字滚动效果实现_第1张图片
滚动字.gif

你可能感兴趣的:(文字滚动效果实现)