iOS开发-三种倒计时的写法

iOS开发-三种倒计时的写法

1.通过NSThread的performSelectorInBackground;
2.通过定时器,属于比较简单的写法;
3.通过GCD中的dispatch_source;

先说第一种 1 .通过NSThread:

#import "ViewController.h"

@interface ViewController ()
{
    int _count;
    UILabel *_label;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 40)];
    _label.backgroundColor=[UIColor greenColor];
    _label.textAlignment=NSTextAlignmentCenter;
    _label.font=[UIFont systemFontOfSize:30];
    _label.text=@"60";
    [self.view addSubview:_label];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

     //多线程读秒操作(可以加在button里控制)
    [self performSelectorInBackground:@selector(thread) withObject:nil];
}

// 在异步线程中无法操作UI,如果想要操作UI必须回调主线程
- (void)thread
{
    for(int i=59;i>=0;i--)
    {
        _count = i;

        // 回调主线程
        [self performSelectorOnMainThread:@selector(mainThread) withObject:nil waitUntilDone:YES];

         //一秒一次
        sleep(1);
    }
}

// 此函数主线程执行
- (void)mainThread
{
    _label.text=[NSString stringWithFormat:@"%d",_count];
    if (_count==0) {
           //这里操作倒计时结束后的事情
           _label.text=@"重新发送";
    }
}
@end

第二种 2 通过定时器:

#import "ViewController.h"

@interface ViewController ()
{
    UIButton *btn;
    int timeDown; //60秒后重新获取验证码
    NSTimer *timer;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=CGRectMake(10, 200, 300, 50);
    btn.backgroundColor=[UIColor cyanColor];
    [btn setBackgroundImage:[UIImage imageNamed:@"bg_send_validate_code.png"] forState:UIControlStateNormal];
    [btn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

- (void)btnAction{
    timeDown = 59;
    [self handleTimer];
    timer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self        selector:@selector(handleTimer) userInfo:nil repeats:YES];
}

-(void)handleTimer
{

    if(timeDown>=0)
    {
        [btn setUserInteractionEnabled:NO];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        int sec = ((timeDown%(24*3600))%3600)%60;
        [btn setTitle:[NSString stringWithFormat:@"(%d)重发验证码",sec] forState:UIControlStateNormal];

    }
    else
    {
        [btn setUserInteractionEnabled:YES];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setTitle:@"重发验证码" forState:UIControlStateNormal];

        [timer invalidate];

    }
    timeDown = timeDown - 1;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

第三种 3 通过GCD中的dispatch_source:

#import "ViewController.h"

@interface ViewController ()
{
    UIButton *_getNumBtn;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _getNumBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    _getNumBtn.frame=CGRectMake(10, 200, 300, 50);
    [_getNumBtn setBackgroundImage:[UIImage imageNamed:@"bg_send_validate_code.png"] forState:UIControlStateNormal];
    [_getNumBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_getNumBtn addTarget:self action:@selector(getNumBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_getNumBtn];
}

- (void)getNumBtnAction{

    __block NSInteger second = 60;
    //全局队列    默认优先级
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //定时器模式  事件源
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
    //NSEC_PER_SEC是秒,*1是每秒
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), NSEC_PER_SEC * 1, 0);
    //设置响应dispatch源事件的block,在dispatch源指定的队列上运行
    dispatch_source_set_event_handler(timer, ^{
        //回调主线程,在主线程中操作UI
        dispatch_async(dispatch_get_main_queue(), ^{
            if (second >= 0) {
                [_getNumBtn setTitle:[NSString stringWithFormat:@"(%ld)重发验证码",second] forState:UIControlStateNormal];
                second--;
            }
            else
            {
                //这句话必须写否则会出问题
                dispatch_source_cancel(timer);
                    [_getNumBtn setTitle:@"获取验证码" forState:UIControlStateNormal];

            }
        });
    });
    //启动源
    dispatch_resume(timer);


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

你可能感兴趣的:(NSTimer)