項目中可能會遇到有些倒計時的地方
比如 手機驗證的時候,驗證碼一般都會有一個時間限制,此時在輸入驗證碼的地方就需要展示一個倒計時
具體實現方式是使用了iOS 自帶的 NSTimer
上代碼
首先新建
int secondsCountDown; //倒計時總時長
NSTimer *countDownTimer;
UILabel *labelText;
然後具體實現
//創建UILabel 添加到當前view
labelText=[[UILabel alloc]initWithFrame:CGRectMake(10, 120, 120, 36)];
[self.view addSubview:labelText];
//設置倒計時總時長
secondsCountDown = 60;//60秒倒計時
//開始倒計時
countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES]; //啟動倒計時後會每秒鐘調用一次方法 timeFireMethod
//設置倒計時顯示的時間
labelText.text=[NSString stringWithFormat:@%d,secondsCountDown];
-(void)timeFireMethod{
//倒計時-1
secondsCountDown--;
//修改倒計時標簽現實內容
labelText.text=[NSString stringWithFormat:@%d,secondsCountDown];
//當倒計時到0時,做需要的操作,比如驗證碼過期不能提交
if(secondsCountDown==0){
[countDownTimer invalidate];
[labelText removeFromSuperview];
}
}
大致已經實現,有問題可繼續交流