文字滚动效果实现

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

//创建
- (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<UITouch *> *)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++;
    
}

实现效果如下

滚动字.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,785评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,245评论 4 61
  • 谁,吻我之眸,遮我半世流离;​ 谁,抚我之面,慰我半世哀伤;​ 谁,携我之心,融我半世冰霜;​ 谁,扶我之肩,驱我...
    吴温暖阅读 3,077评论 0 0
  • 原英文文档 import 创建对象 通过list创建Series,pandas创建默认的整数索引 通过numpy ...
    charmler阅读 8,415评论 0 3
  • 走还是不走,再也不是问题 图书馆前那片草坪不太平已经很久了,每年总是会在学校贴吧里面掀起点涟漪,或在社团活动中露露...
    赖床的熊二阅读 3,255评论 0 0