计时器


下面是一个读秒倒计时例子,按 分钟:秒 显示。


首先是三个相关的属性。

@property(nonatomic,strong)UILabel* btnVerify;//定时器lable
@property(nonatomic,assign)int seconds;//获取到的剩余支付时间的秒数
@property(nonatomic,strong)NSTimer* clockTimer;//定时器


-(void)initMyClockView:(int)x
{

               // x :倒计时需要的秒数

                if(x>0)
                {
                    NSString *result = [NSString stringWithFormat:@"%d",x];
                    
                    _btnVerify = [[UILabel alloc] initWithFrame:CGRectMake(160, 0, SCREEN_WIDTH-160, 44)];
                    _btnVerify.textAlignment = NSTextAlignmentLeft;
                    _btnVerify.textColor = [UIColor hexStringToColor:@"ff0000"];
                    _btnVerify.font = [UIFont systemFontOfSize:13];
                    [self.View addSubview:_btnVerify];
                    [self startCountDown:result];
                }

}

#pragma mark - 启动定时器
- (void)startCountDown:(NSString* )strx
{
    _seconds = [strx intValue];
    
    int a = _seconds/60;//分钟
    int b = _seconds%60;//秒数
    
    NSMutableString* strb = [NSMutableString stringWithFormat:@"%d",b];
    if([strb length] == 1)
    {
        strb = [NSMutableString stringWithFormat:@"0%d",b];
    }
        
    NSString *str = [NSString stringWithFormat:@"%d:%@秒后订单失效", a,strb];
    
    _btnVerify.text = str;


/*

初始化时也可以使用scheduled开头的方法初始化,会把默认mode直接添加到当前的runloop中。

这里使用的是另外一种自写的方法。自动触发。

*/   
    _clockTimer = [NSTimer timerWithTimeInterval:1
                                          target:self
                                        selector:@selector(oneSecondPass)
                                        userInfo:nil
                                         repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_clockTimer forMode:NSDefaultRunLoopMode];
}


- (void)oneSecondPass
{
    if (_seconds > 0)
    {
        _seconds = _seconds - 1;
        
        int a = _seconds/60;//分钟
        int b = _seconds%60;//秒数
        NSMutableString* strb = [NSMutableString stringWithFormat:@"%d",b];
        if([strb length] == 1)
        {
            strb = [NSMutableString stringWithFormat:@"0%d",b];
        }
        NSString *str = [NSString stringWithFormat:@"%d:%@秒后订单失效", a,strb];
        
        _btnVerify.text = str;
    }

  else

  {

        [_clockTimer invalidate];//结束定时器要先使其失效,从runloop中移出
        _clockTimer = nil;
        
        _btnVerify.text = @" ";
       
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值