倒计时在发送验证码是常见的功能,怎么实现这个功能。正所谓会者不难,难者不会。在此遍博客来实现一下。具体代码可以参考 倒计时Demo
一、实现思路
倒计时功能的实现:
当触发倒计时的button时,才进行倒计时功能
倒计时完毕时,使button可用即可以再次点击来重新发送
二、具体代码的实现
EDCountdown.h
//
// EDCountdown.h
// Countdown
//
// Created by humor on 15/12/31.
// Copyright © 2015年 onefiter. All rights reserved.
//
#import <Foundation/Foundation.h>
@class EDCountdown;
@protocol EDCountdownDelegate <NSObject>
/**
* 周期性的通知外界,自创建计时器到当前时间差值
*
* @param sender 计时器
* @param timeOffset 自创建计时器到当前时间差值
*/
- (void)notifyCountTimeCallBack:(id)sender withTimeOffset:(NSTimeInterval)timeOffset;
@end
@interface EDCountdown : NSObject
@property(nonatomic, weak ) id<EDCountdownDelegate> delegate;
@property(nonatomic, assign) BOOL isOpen;
@property(nonatomic, assign) NSTimeInterval timeInterval;
- (void)handleCountTimerEvent:(id)sender;
@end
EDCountdown.m
//
// EDCountdown.m
// Countdown
//
// Created by humor on 15/12/31.
// Copyright © 2015年 onefiter. All rights reserved.
//
#import "EDCountdown.h"
@interface EDCountdown ()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSTimeInterval startTime;
@end
@implementation EDCountdown
- (instancetype)init
{
if (self = [super init]) {
_timeInterval = 1;
}
return self;
}
- (void)dealloc
{
self.isOpen = NO;
}
- (void)setIsOpen:(BOOL)isOpen
{
_isOpen = isOpen;
__block dispatch_block_t mainBlock = NULL;
if (_isOpen) {
mainBlock = ^{
if (_timer.isValid) {
[_timer invalidate];
}
_timer = [NSTimer scheduledTimerWithTimeInterval:_timeInterval target:self selector:@selector(handleCountTimerEvent:) userInfo:nil repeats:YES];
_startTime = CFAbsoluteTimeGetCurrent();
};
}
else
{
mainBlock = ^{
if (_timer.isValid) {
[_timer invalidate];
}
_timer = nil;
};
}
if ([NSThread isMainThread]) {
mainBlock();
}
else
{
dispatch_async(dispatch_get_main_queue(), mainBlock);
}
}
- (void)handleCountTimerEvent:(id)sender
{
if ([_delegate respondsToSelector:@selector(notifyCountTimeCallBack:withTimeOffset:)]) {
NSTimeInterval deltaTime = CFAbsoluteTimeGetCurrent() - _startTime;
[_delegate notifyCountTimeCallBack:self withTimeOffset:deltaTime];
}
}
@end