我使用 UILabel
和 NSTimer
显示倒计时器 -
-(void)a_Method
{
[coolTimeLbl setNeedsDisplay];
coolTime = 5; // it is an int
coolingTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(cooling) userInfo:nil repeats:YES]; // NSTimer
}
-(void)cooling
{
if (coolTime>0)
{
coolTime = coolTime-1;
NSLog(@" coolTime----%@",coolTime);
coolTimeLbl.text =[NSString stringWithFormat:@"%d",coolTime];
NSLog(@" coolTimeLbl----%@",coolTimeLbl.text);
}
else
{
[coolingTimer invalidate];
coolingTimer = nil;
}
}
第一次一切正常,我得到 coolTimeLbl.text
为 - 4 3 2 1 0
但是当我第二次调用 aMethod
时,coolTimeLbl
没有正确更新 - 它就像 3 2 0 等(一些奇怪的行为)
然而,NSLogs
(coolTime
和 coolTimeLbl
) 完美地打印了所有时间和值。
为什么会这样?我尝试了很多方法,例如 NSNotification
等。
请帮我解决这个问题。
最佳答案
如果您在 coolingTimer 自身失效之前多次调用 a_Method,则计时器将计时多次。
你应该添加一些 bool 值,比如;
BOOL isTimerValid;
在a_Method中,
if(!isTimerValid)
{
isTimerValid = YES;
coolingTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(cooling) userInfo:nil repeats:YES]; // NSTimer
}
冷却中,
else
{
isTimerValid = NO;
....
}
关于ios - UILabel 使用 NSTimer 更新不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25146235/