下面是一个读秒倒计时例子,按 分钟:秒 显示。
首先是三个相关的属性。
@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 = @" ";
}
}