ios - UILabel 使用 NSTimer 更新不正确

标签 ios objective-c uilabel nstimer

我使用 UILabelNSTimer 显示倒计时器 -

-(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 (coolTimecoolTimeLbl) 完美地打印了所有时间和值。

为什么会这样?我尝试了很多方法,例如 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/

相关文章:

ios - 无法使用 http URL 加载我的 WebView

ios - 居中 UILabel subview

swift - 无法更改 UILabel [Swift] 上的 UIFont 大小

ios - 动态移动(动画)UITextField

objective-c - @""和 @"123"之间有什么不同吗?

ios - 在 iOS 上,如果 drawRect 不使用传入的矩形,那么 [self setNeedsDisplayInRect :rect] passes in a rect? 是否重要

objective-c - 在 Swift 3 中从 Objective-C calloc 重构

ios - Objective C 运算符优先级

ios - 我如何获得 Alamofire get-request 的 location-header?

ios - swift:以编程方式创建 UILabel 固定宽度,根据文本长度垂直调整大小