簡體   English   中英

iOS:UILabel倒數計時會掛在其他UI操作上

[英]iOS: UILabel countdown hangs on other UI operation

我正在實現一個倒計時,其值顯示在UILabel上,但是遇到了問題。 這是簡化的代碼:

self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countdown) userInfo:nil repeats:YES];

- (void)countdown {          
     self.countdownLabel.text = [NSString stringWithFormat:@"%i",[self.countdownLabel.text intValue]-1];

     // Handle time out
     if ([self.countdownLabel.text intValue] == 0) {
             [self.countdownTimer invalidate];
             self.countdownTimer = nil;
     }
}

它工作正常,但是如果我在視圖控制器中執行其他UI操作(例如滾動滾動視圖),則計時器會在滾動視圖滾動時掛起 ,然后升空以彌補空閑時間。

我嘗試將標簽的更新分派到后台隊列,這當然是行不通的。

dispatch_queue_t bgQ = dispatch_queue_create("bgQ", 0);
dispatch_async(bgQ, ^{
    self.countdownLabel.text = [NSString stringWithFormat:@"%i",[self.countdownLabel.text intValue]-1];
});

這里的解決方案是什么?

self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countdown) userInfo:nil repeats:YES];    
[[NSRunLoop mainRunLoop] addTimer:self.countdownTimer forMode:NSRunLoopCommonModes];

請記住,在您的倒數方法中,您需要進行轉義以使您的倒數計時器無效。

[[NSRunLoop mainRunLoop] addTimer:self.countdownTimer forMode:NSRunLoopCommonModes];

行被執行。 絕對沒有用戶界面更改的調度異步。

希望這可以幫助。

Swift 3.0語法

var timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(ViewController.updateTimer), userInfo: nil, repeats: true);
RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM