项目中可能会遇到有些倒计时的地方
比如 手机验证的时候,验证码一般都会有一个时间限制,此时在输入验证码的地方就需要展示一个倒计时
使用了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];
- }
- }