我想为我的 UILabel 制作动画,使其看起来像向上计数。为了便于讨论,我们只是说我希望它每秒增加 1。
以下方法均无效。
一个简单的 for 循环(此处的示例)不起作用,因为它太快了。
for(int i =0;i<1000;i++)
{
lblNum.text = [NSString stringWithFormat:@"%d",i];
}
添加 sleep(1) 不起作用,因为执行是异步的(我认为至少这就是原因)
我也尝试过:
for(int i=0;i<1000;i++)
{
[self performSelector:@selector(updateLbl:)
withObject:[NSNumber numberWithInt:i ] afterDelay:1];
}
-(void)updateLbl:(NSNumber *)num
{
lblNum.text = [NSString stringWithFormat:@"%@",num];
}
还有:
for(int i=0;i<1000;i++)
{
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
// Do something...
sleep(1);
dispatch_async(dispatch_get_main_queue(), ^{
lblNum.text = [NSString stringWithFormat:@"%d",i];
});
});
}
最佳答案
NSTimer *timer = [NSTimer scheduleTimerWithTimeInterval:1.0 target:self selector:@selector(increment:) userInfo:label repeats:YES];
...
- (void)increment:(NSTimer *)timer {
UILabel *label = (UILabel *)timer.userInfo;
NSInteger i = label.text.integerValue;
i++;
label.text = [NSString stringWithFormat:@"%d", i];
if(someCondition){
[timer invalidate]//stops calling this method
}
}
关于iOS:向上计数动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18583918/