MZTimerLabel是UILabel的一个子类,它可以将UIlable作为一个倒计时器或秒表使用,和苹果的系统时间应用一样,仅仅只需要两行代码。MZTimer同时还提供了委托方法,当计时结束后可以自己定义action。
需要
ARC
iOS 5.0+
简易示例
使用MZTimerLabel作为秒表或者计时器 ,你只需要以下两行代码:
MZTimerLabel *stopwatch = [[MZTimerLabel alloc] initWithLabel:aUILabel];
[stopwatch start];
简单吧,如果想要一个倒计时表,也差不多:
MZTimerLabel *timer = [[MZTimerLabel alloc] initWithLabel:aUILabel andTimerType:MZTimerLabelTypeTimer];
[timer setCountDownTime:60];
[timer start];
这样的话,会从60s开始倒计时。
定制外观
由于MZTimerLabel是一个UILabel的子类,你可以直接将它作为一个普通的UILable来分配它,然后定制timeLabel属性。
MZTimerLabel *redStopwatch = [[MZTimerLabel alloc] init];
redStopwatch.frame = CGRectMake(100,50,100,20);
redStopwatch.timeLabel.font = [UIFont systemFontOfSize:20.0f];
redStopwatch.timeLabel.textColor = [UIColor redColor];
[self.view addSubview:redStopwatch];
[redStopwatch start];
MZTimerLabel的时间格式是:00:00:00 (小时HH:分钟mm:秒ss),如果你希望使用其他的格式,你也可以自己调整,比如说你希望有毫秒的显示,则可以:
timerExample4.timeFormat = @"HH:mm:ss SS";
控制计时器
你可以通过定制的控件来开始,暂停以及重置计时器,启用这几个计时器,调用以下方法:
-(void)start;
-(void)pause;
-(void)reset;
计时器结束之后的处理方法
一般来说,你需要处理一下计时器使用完毕之后的情况。这里提供了两个方法。
Delegate
首先,这是计时器label的delegate
timer.delegate = self;
然后实现MZTimerLabelDelegate协议:
@interface ViewController : UIViewController
最后,实现委托方法:timerLabel:finshedCountDownTimerWithTimeWithTime:
-(void)timerLabel:(MZTimerLabel*)timerLabel finshedCountDownTimerWithTime:(NSTimeInterval)countTime{
//time is up, what should I do master?
}
Blocks
Blcok用来处理回调非常方便:
MZTimerLabel *timer = [[MZTimerLabel alloc] initWithLabel:aUILabel andTimerType:MZTimerLabelTypeTimer];
[timer3 setCountDownTime:60];
[timer startWithEndingBlock:^(NSTimeInterval countTime) {
//oh my god it's awesome!!
}];