There are two ways to countdown: 1. Nstimer 2.GCD
Design ideas: The view has a label and Button,label with Nstimer Countdown, button with GCD, click button simultaneously countdown, 5 seconds after the stop
On the code:
In @interface:
@property (assign,nonatomic) int numer;
@property (strong,nonatomic) nstimer * timer;
@property (strong,nonatomic) UILabel * label;
@property (strong,nonatomic) UIButton * BTN;
In 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 (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:@ "click" Forstate:uicontrolstatenormal];
[Self.view ADDSUBVIEW:BTN];
SELF.BTN=BTN;
Button method and Nstimer method:
-(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; Countdown time
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); Executes per second
Dispatch_source_set_event_handler (Timers, ^{
if (timeout<=0) {//Countdown end, close
Dispatch_source_cancel (timers);
Dispatch_async (Dispatch_get_main_queue (), ^{
Set the interface button to display the settings according to your needs
[Self.btn settitle:@ "click" Forstate:uicontrolstatenormal];
BTN can click
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 minutes%.2d seconds", minutes, seconds];
Dispatch_async (Dispatch_get_main_queue (), ^{
Set the interface button to display the settings according to your needs
[Self.btn settitle:strtime Forstate:uicontrolstatenormal];
BTN No Click
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];
[Email protected] "no";
}
}
IOS Countdown method