2017-02-05 38 views
0

我想在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

只需将'delayInSeconds'更改为'i * 5'即可。 – rmaddy

回答

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]; 

} 

我写了这头我的头,并没有编译它,但它看起来应该或多或少这样。