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

时间:2017-02-05 21:47:07

标签: ios objective-c

我想在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;
        });        
    }
}

1 个答案:

答案 0 :(得分:0)

你正在创建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];

}

我把这个脑袋写下来并没有编译它,但它应该看起来或多或少像这样。