MZTimerLabel是一个UILabel子类,它使用UILabel作为倒计时器或计时器的方式非常方便,就像Apple时钟应用中的那样,只需两行代码即可。MZTimerLabel还为您提供了代理方法,以定义计时器完成时的操作。
作者:MineS Chan和令人敬畏的贡献者。
注释:这是我第一个在github上的iOS插件项目,如果代码有任何不佳之处,请谅解。
MZTimerLabel.h
和MZTimerLabel.m
源文件添加到您的项目中。要将MZTimerLabel用作计时器和计数器,您只需要两行代码。
MZTimerLabel *stopwatch = [[MZTimerLabel alloc] initWithLabel:aUILabel];
[stopwatch start];
很简单?如果您在找计时器,方法也是类似的。
MZTimerLabel *timer = [[MZTimerLabel alloc] initWithLabel:aUILabel andTimerType:MZTimerLabelTypeTimer];
[timer setCountDownTime:60];
[timer start];
现在计时器将从60开始倒数到0 ;)
由于MZTimerLabel是UILabel的子类,您可以像正常分配UILabel一样分配它,并自定义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;
您可以使用这些属性和方法在运行时控制时间值和行为。
@property (assign) BOOL shouldCountBeyondHHLimit; //see example #12
@property (assign) BOOL resetTimerAfterFinish; //see example #7
-(void)setCountDownTime:(NSTimeInterval)time;
-(void)setStopWatchTime:(NSTimeInterval)time;
-(void)setCountDownToDate:(NSDate*)date;
-(void)addTimeCountedByTime:(NSTimeInterval)timeToAdd; //see example #10, #11
如果您想了解计时器的信息,这里是如何操作的。
@property (assign,readonly) BOOL counting; //see example #4-7
- (NSTimeInterval)getTimeCounted; //see example #3
- (NSTimeInterval)getTimeRemaining; //see example #3
- (NSTimeInterval)getCountDownTime;
通常,当您需要计时器时,您需要在它结束后处理它。以下两个示例显示了如何使用delegate
和block
方法完成此操作。
首先,设置计时器标签的委托。
timer.delegate = self;
然后,在您的专用类中实现 MZTimerLabelDelegate
协议
@interface ViewController : UIViewController<MZTimerLabelDelegate>
最后,实现委托方法 timerLabel:finshedCountDownTimerWithTimeWithTime:
-(void)timerLabel:(MZTimerLabel*)timerLabel finshedCountDownTimerWithTime:(NSTimeInterval)countTime{
//time is up, what should I do master?
}
块是一种处理回调的非常方便的方式,MZTimerLabel使您的生命周期变得更简单。
MZTimerLabel *timer = [[MZTimerLabel alloc] initWithLabel:aUILabel andTimerType:MZTimerLabelTypeTimer];
[timer3 setCountDownTime:60];
[timer startWithEndingBlock:^(NSTimeInterval countTime) {
//oh my gosh, it's awesome!!
}];
或单独设置它
[timer3 setCountDownTime:60];
timer.endedBlock = ^(NSTimeInterval countTime) {
//oh my gosh, it's awesome!!
};
[timer start];
请查看我提供的示例项目,其中包含详细说明的示例代码。
本代码遵循MIT协议的条款和条件。