iOS:向上计数动画
我想设置UILabel的动画,使其看起来像是向上计数。为了论证起见,让我们说我希望它每秒上升1 以下方法都不能正常工作 一个简单的for循环(这里的例子)不起作用,因为它的速度太快了iOS:向上计数动画,ios,objective-c,cocoa-touch,Ios,Objective C,Cocoa Touch,我想设置UILabel的动画,使其看起来像是向上计数。为了论证起见,让我们说我希望它每秒上升1 以下方法都不能正常工作 一个简单的for循环(这里的例子)不起作用,因为它的速度太快了 for(int i =0;i<1000;i++) { lblNum.text = [NSString stringWithFormat:@"%d",i]; } for(inti=0;i我认为这样做的一个好方法是使用NSTimer 实现很简单,只需将repeat设置为YES并使计时器每秒启动一次。您可以
for(int i =0;i<1000;i++)
{
lblNum.text = [NSString stringWithFormat:@"%d",i];
}
for(inti=0;i我认为这样做的一个好方法是使用NSTimer
实现很简单,只需将repeat设置为YES并使计时器每秒启动一次。您可以让一个变量跟踪count并每次增加它
编程的一个很好的经验法则是:永远不要使用睡眠!!使用NSTimer
&nsrunlop
在代码中执行动画
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
}
}
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
}
}
是的,就这样了:)谢谢!这很好,但将NSTimer*计时器更改为:[NSTimer scheduledTimerWithTimeInterval:(1.5/分数)目标:自选择器:@selector(增量:)userInfo:self.scoreLabel repeats:YES];避免未使用的变量。
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
}
}
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
}
}