2012-07-27 159 views
0

我是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); 
    } 
} 

我怎樣才能解決這個問題,好嗎?

+2

這個任務是一個完美的動畫作業。除非有某些原因你不能*使用它們,否則這將是一條路。 http://developer.apple.com/library/ios/#documentation/windowsviews/conceptual/viewpg_iphoneos/animatingviews/animatingviews.html – Brian 2012-07-27 12:41:03

+0

你可以看看我的答案在下面2鏈接 的http://計算器問題/ 11661720/trouble-setting-label-text-in-ios/11661920#11661920 http://stackoverflow.com/questions/11686642/each-charecter-animation-for-uilable/11687672# 11687672 – cloosen 2012-07-27 12:54:51

回答

1

要停止計時器,請執行[timer invalidate]

你不能「暫停」一個定時器,所以一旦你這樣做,你需要調用另一個定時器。

4

如果你想停止重複計時器,您可以使用

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;}]; 
1

正確的方法無效你的計時器是

[myTimer invalidate]; 
myTimer = nil;