如何停止重复计时器?
问题描述:
我是iOS应用程序开发的初学者。我想从左向右移动一个标签,直到它达到屏幕宽度的一半 - 即标签应该移动240px(标签像一个选取框一样左右移动)。如何停止重复计时器?
我已经使用NSTimer,并且当标签达到视图宽度的一半时,我想停止计时器。
我用下面的代码,但它移动的标签出来的观点:
- (void)viewDidLoad {
[super viewDidLoad];
timer = [[NSTimer scheduledTimerWithTimeInterval:0.09 target:self selector:@selector(time:) userInfo:nil repeats:YES] retain];
}
- (void)time:(NSTimer *)theTimer {
label.center = CGPointMake(label.center.x+3.5, label.center.y);
NSLog(@"point:%@", label);
if (label.center.x < - (label.bounds.size.width/2)) {
label.center = CGPointMake(320+(label.bounds.size.width/2), label.center.y);
}
}
我怎样才能解决这个问题,好吗?
答
要停止计时器,请执行[timer invalidate]
。
你不能“暂停”一个定时器,所以一旦你这样做,你需要调用另一个定时器。
答
如果你想停止重复计时器,您可以使用
if (/*You label is in position*/)
[myTimer invalidate];
但是,这不是做在iOS的动画以正常的方式,尝试此相反:
CGRect endFrame = /*The frame of your label in end position*/
[UIView animateWithDuration:0.5 animations:^{ myLabel.frame = endFrame;}];
答
正确的方法无效你的计时器是
[myTimer invalidate];
myTimer = nil;
这个任务是一个完美的动画作业。除非有某些原因你不能*使用它们,否则这将是一条路。 http://developer.apple.com/library/ios/#documentation/windowsviews/conceptual/viewpg_iphoneos/animatingviews/animatingviews.html – Brian 2012-07-27 12:41:03
你可以看看我的答案在下面2链接 的http://计算器问题/ 11661720/trouble-setting-label-text-in-ios/11661920#11661920 http://*.com/questions/11686642/each-charecter-animation-for-uilable/11687672# 11687672 – cloosen 2012-07-27 12:54:51