iOS:向上计数动画

标签 ios objective-c cocoa-touch

我想为我的 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/

相关文章:

ios - ivar 在 block 内为 null,尽管在 block 执行之前设置

objective-c - 如何在 Objective-C 中获取我的文件大小

ios - block 内的强弱。我该如何处理这个问题?

iphone - 应用内购买完成后显示对话

ios - 在 objective-c 中创建默认变量(对象)

iOS7 与 Xcode 6 的兼容性

ios - 使用 Swift 进行 PubNub 和解析?

ios - 使用 CGImageDestinationCopyImageSource 时 CGImageDestinationFinalize 失败

ios - 拒绝视频通话后弹出视频通话?

iphone - 在 LoadView 中居中 UIView