一、前言
今天碰到一個需求愉烙,仿全民直播的321倒計時動畫狰住,類似下圖的效果,其實仔細想想并不難齿梁,但在網(wǎng)上找了下,有的做的還是有點復雜了肮蛹,在這里分享下我的做法勺择。
未命名.gif
二、分析
無非就是一個倒計時伦忠,這里NSTimer實現(xiàn)省核,然后一個Label,并且對Label里的數(shù)字實施動畫,產(chǎn)生如圖的效果昆码。這里動畫采用的是CAKeyframeAnimation气忠,因為它可以設置變化數(shù)組,符合我們的放大縮小復原需求赋咽。
三旧噪、代碼
這里自定義了個CountdownLabel繼承制UILabel,并在內(nèi)部實現(xiàn)了倒計時脓匿,默認開始時間是3淘钟。
//.h文件
#import <UIKit/UIKit.h>
@interface CountdownLabel : UILabel
//開始倒計時時間
@property (nonatomic, assign) int count;
//執(zhí)行這個方法開始倒計時
- (void)startCount;
@end
//.m文件
#import "CountdownLabel.h"
@interface CountdownLabel()
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation CountdownLabel
//開始倒計時
- (void)startCount{
[self initTimer];
}
- (void)initTimer{
//如果沒有設置,則默認為3
if (self.count == 0){
self.count = 3;
}
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
}
- (void)countDown{
if (_count > 0){
self.text = [NSString stringWithFormat:@"%d",_count];
CAKeyframeAnimation *anima2 = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
//字體變化大小
NSValue *value1 = [NSNumber numberWithFloat:3.0f];
NSValue *value2 = [NSNumber numberWithFloat:2.0f];
NSValue *value3 = [NSNumber numberWithFloat:0.7f];
NSValue *value4 = [NSNumber numberWithFloat:1.0f];
anima2.values = @[value1,value2,value3,value4];
anima2.duration = 0.5;
[self.layer addAnimation:anima2 forKey:@"scalsTime"];
_count -= 1;
}else {
[_timer invalidate];
[self removeFromSuperview];
}
}
具體用法
#import "CountdownLabel.h"
...
...
//倒計時動畫
- (void)initCountdownLabel{
CountdownLabel *countdownLabel = [[CountdownLabel alloc] initWithFrame:CGRectMake(0, 350, 100, 30)];
countdownLabel.textAlignment = NSTextAlignmentCenter;
countdownLabel.textColor = [UIColor whiteColor];
countdownLabel.font = [UIFont systemFontOfSize:25];
[self.view addSubview:countdownLabel];
//可以在合適的地方 -開始倒計時
[countdownLabel startCount];
}
四陪毡、總結(jié)
代碼已上傳GitHub
如果你想直接使用米母,就下載代碼,將HHCountdownLabel直接拖入項目使用吧毡琉,label的初始化都是一樣的铁瞒,只是在顯示的地方調(diào)用方法startCount就可以了。
實現(xiàn)一個功能有很多種方法桅滋,我這個方法怎么樣呢慧耍,感覺對你有幫助的話給個贊吧。