我想为我的UILabel设置动画,使其看起来像向上计数。为了论证,我们只想说我希望它每秒上升一次。
以下任何一种方式都无法正常运作。
一个简单的for循环(这里的例子)不起作用,因为它太快了。
for(int i =0;i<1000;i++)
{
lblNum.text = [NSString stringWithFormat:@"%d",i];
}
添加睡眠(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];
});
});
}
答案 0 :(得分:1)
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
}
}
答案 1 :(得分:0)
我认为这样做的好方法是使用NSTimer。
实现很简单,只需将repeat设置为YES并使计时器每秒触发一次。您可以使用变量跟踪计数并每次增加它。
编程的一个好的经验法则:永远不要睡觉!
答案 2 :(得分:0)
使用NSTimer
&amp; NSRunLoop
在您的代码中执行动画
timer_=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(labelAnimation:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer_ forMode:NSDefaultRunLoopMode];
- (void)increment:(NSTimer *)timer
{
if(isAnimationComplete)
{
[timer_ invalidate]//stops calling this method
}
else
{
//perform your action
}
}