我想在iOS设备上从0数到9,但我总是只看到数字9。我设置了一个计时器来放慢速度,并显示每个数字5秒钟,但它不起作用。我只看到数字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;
});
}
}发布于 2017-02-06 06:04:21
您正在创建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];
}我从头脑中写出了这个头,并没有编译它,但它或多或少应该看起来像这样。
https://stackoverflow.com/questions/42057715
复制相似问题