如何延迟计数或显示数字变化



我想在iOS设备上从0数到9,但我总是只看到数字9。我放了一个计时器来放慢速度并显示每个数字五秒钟,但它不起作用。我只看到数字9。如何按顺序查看数字(0,1,2,3,..(?

任何人都可以帮助我解决这个问题吗?

- (IBAction)btnStart:(id)sender {
    for(int i=0; i<10; i++) {
        NSString* myNewString = [NSString stringWithFormat:@"%d", i];
        int64_t delayInSeconds = 5;
        dispatch_time_t popTime = 
            dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
            _lbCounter.text =myNewString;
        });        
    }
}

您正在创建 10 个调度,它们将在 5 秒后全部触发,在眨眼间发生的主队列上。

你最好使用NSTimer

- (void)viewDidLoad {
...
// Fire `incrementLabel` every 5 seconds infinitely (repeats: YES)
self.currentTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
    target:self
    selector:@selector(incrementLabel:)
    userInfo:nil
    repeats:YES];
...
}
- (void)incrementLabel {
   self.currentCounter++;
   if (self.currentCounter == 10) {
     [self.currentTimer invalidate]
     return;
   }
    _lbCounter.text = [NSString stringWithFormat:@"%ld", self.currentCounter];
}

我把这个头从我的脑海里写出来,没有编译它,但它应该或多或少看起来像这样。

最新更新