iOS 动态改变数字效果 核心代码

作者: KumLight | 来源:发表于2016-12-01 15:02 被阅读252次

前言

常常会看到 数字 0 动态变化 到 100 的这种效果 .
GitHub 上相关的Demo 也有很多 .
比如 UICountingLabel , DDKit( UILabel+FlickerNumber )

大致效果呢就是这个样子


UICountingLabel

虽说轮子很好 , 但需求稍微一改 , 没有相应的API 接口就很尴尬了 .
所以准备剖析一下, 这种效果的核心代码到底是什么


我准备做的效果是 从 高位数 到 低位数 的动态变化 .

大致思路就是用NSTimer 控制变化速度 , 然后在NSTimer 的userInfo 参数里面添加一个可变字典 , 加入起始数据 和终止数据 . 然后在回调方法里对 userInfo 里的数据进行处理 , 最终达到动态变化的效果 .

按钮的点击事件 , 防止动画没结束时 重复调用 .

- (IBAction)beginAnimation:(UIButton *)sender {
    
    if (!self.timer) {
        
        [self labelAnimationBegin:50 End:20];
        
    }
}

将 起始数字与终止数字 添加到NSTimer的 userInfo中.

- (void)labelAnimationBegin:(int)begin End:(int)end{

    NSMutableDictionary *userinfo = [NSMutableDictionary dictionary];
    
    [userinfo setObject:@(begin) forKey:@"beginNumber"];
    [userinfo setObject:@(end) forKey:@"endNumber"];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1/20.0 target:self selector:@selector(changeNumberAnimation:) userInfo:userinfo repeats:YES];
    
}

每次减一操作 , 并改变userInfo中 起始数字.

- (void)changeNumberAnimation:(NSTimer *)timer{
    
    int begin = [timer.userInfo[@"beginNumber"] floatValue];
    int end = [timer.userInfo[@"endNumber"] floatValue];
    int current = begin;
    current -= 1;
    
    [timer.userInfo setObject:@(current) forKey:@"beginNumber"];
    
    self.numberLB.text = [NSString stringWithFormat:@"%d",current];
    
    if (current == end) {

        [timer invalidate];
        self.timer = nil;

    }
}

最后效果是这样的 .
在这基础上就可以进行各种的封装了.

效果图

相关文章

网友评论

    本文标题:iOS 动态改变数字效果 核心代码

    本文链接:https://www.haomeiwen.com/subject/zivxmttx.html