iOS之实现倒计时功能

倒计时在发送验证码是常见的功能,怎么实现这个功能。正所谓会者不难,难者不会。在此遍博客来实现一下。具体代码可以参考 倒计时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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值