前言
常常會(huì)看到 數(shù)字 0 動(dòng)態(tài)變化 到 100 的這種效果 .
GitHub 上相關(guān)的Demo 也有很多 .
比如 UICountingLabel , DDKit( UILabel+FlickerNumber )
大致效果呢就是這個(gè)樣子
UICountingLabel
雖說(shuō)輪子很好 , 但需求稍微一改 , 沒(méi)有相應(yīng)的API 接口就很尷尬了 .
所以準(zhǔn)備剖析一下, 這種效果的核心代碼到底是什么
我準(zhǔn)備做的效果是 從 高位數(shù) 到 低位數(shù) 的動(dòng)態(tài)變化 .
大致思路就是用NSTimer 控制變化速度 , 然后在NSTimer 的userInfo 參數(shù)里面添加一個(gè)可變字典 , 加入起始數(shù)據(jù) 和終止數(shù)據(jù) . 然后在回調(diào)方法里對(duì) userInfo 里的數(shù)據(jù)進(jìn)行處理 , 最終達(dá)到動(dòng)態(tài)變化的效果 .
按鈕的點(diǎn)擊事件 , 防止動(dòng)畫沒(méi)結(jié)束時(shí) 重復(fù)調(diào)用 .
- (IBAction)beginAnimation:(UIButton *)sender {
if (!self.timer) {
[self labelAnimationBegin:50 End:20];
}
}
將 起始數(shù)字與終止數(shù)字 添加到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中 起始數(shù)字.
- (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;
}
}
最后效果是這樣的 .
在這基礎(chǔ)上就可以進(jìn)行各種的封裝了.
效果圖