倒计时用到了两种方法:1.NSTimer 2.GCD
设计思路:view上有label和button,label用NSTimer倒计时,button用GCD,点击button同时倒计时,5秒后停止
上代码:
@interface里:
@property (assign,nonatomic)int numer;
@property (strong,nonatomic)NSTimer * timer;
@property (strong,nonatomic)UILabel * label;
@property (strong,nonatomic)UIButton * btn;
viewDidLoad里:
self.view.backgroundColor=[UIColor whiteColor];
self.numer=5;
UILabel * label=[[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
label.backgroundColor=[UIColor orangeColor];
label.textAlignment=NSTextAlignmentCenter;
label.textColor=[UIColor whiteColor];
[self.view addSubview:label];
self.label=label;
UIButton * btn=[UIButton buttonWithType:UIButtonTypeCustom];
btn.frame=CGRectMake(100, CGRectGetMaxY(label.frame)+20, 100, 100);
btn.backgroundColor=[UIColor redColor];
[btn addTarget:self action:@selector(bbb) forControlEvents:UIControlEventTouchUpInside];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn setTitle:@"点击" forState:UIControlStateNormal];
[self.view addSubview:btn];
self.btn=btn;
button方法和NSTimer方法:
-(void)bbb
{
self.timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aaa) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
__block int timeout=5; //倒计时时间
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timers = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
dispatch_source_set_timer(timers,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
dispatch_source_set_event_handler(timers, ^{
if(timeout<=0){ //倒计时结束,关闭
dispatch_source_cancel(timers);
dispatch_async(dispatch_get_main_queue(), ^{
//设置界面的按钮显示 根据自己需求设置
[self.btn setTitle:@"点击" forState:UIControlStateNormal];
//btn可以点击
self.btn.userInteractionEnabled=YES;
self.numer=5;
[self.btn addTarget:self action:@selector(bbb) forControlEvents:UIControlEventTouchUpInside];
});
}else{
int minutes = timeout / 60;
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%d分%.2d秒",minutes, seconds];
dispatch_async(dispatch_get_main_queue(), ^{
//设置界面的按钮显示 根据自己需求设置
[self.btn setTitle:strTime forState:UIControlStateNormal];
//btn禁止点击
self.btn.userInteractionEnabled=NO;
});
timeout--;
}
});
dispatch_resume(timers);
}
-(void)aaa
{
self.numer--;
self.label.text=[NSString stringWithFormat:@"%d",self.numer];
if (self.numer==0) {
[self.timer invalidate];
self.label.text=@"没啦";
}
}
原文:http://www.cnblogs.com/tongyuling/p/4647618.html