2014-11-02 44 views
1

我想動畫UILabel的文本,以便它顯示一個文本幾秒鐘,然後淡入默認文本。延遲UILabel中的文本之間的淡入淡出

我目前使用下面的代碼:

-(void)tapOnBalance:(id)sender{ 
     [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ 
     cell.amountLabel.text = @"Hola!"; 
     } completion:nil]; 

     // Pause the function - act as a 'delay' 
     [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3]]; 

     [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{ 
     cell.amountLabel.text = @"Hallo!"; 
     } completion:nil]; 

} 

這工作,但[NSRunLoop currentRunLoop]被暫停整個應用程序,3秒阻止一切。

如何擺脫主線程上的塊並仍然得到相同的結果?

+1

您是否考慮過使用動畫方法的「延遲」參數? – 2014-11-02 19:41:46

+0

是的,但它們不適用於'UILabels' – bdv 2014-11-02 19:42:09

+1

不知道downvote,但(1)在這種情況下不必暫停主線程......利用完成塊並延遲。 (2)看看這個答案,以獲得如何正確執行這種UILabel轉換的幫助:http://stackoverflow.com/a/16367409/2274694 – 2014-11-02 19:54:43

回答

1

一個簡單的淡入淡出(非交叉淡入淡出)可以是這樣的:

// change a label's text after some delay by fading 
// out, changing the text, then fading back in 
- (void)fadeLabel:(UILabel *)label toText:(NSString *)toText completion:(void (^)(BOOL))completion { 
    [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ 
     label.alpha = 0.0; 
    } completion:^(BOOL finished) { 
     label.text = toText; 
     [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{ 
      label.alpha = 1.0; 
     } completion:completion]; 
    }]; 
} 

// simpler signature that can be done on a perform 
- (void)changeLabelText:(NSString *)toText { 
    [self fadeLabel:self.myLabel toText:toText completion:nil]; 
} 

// set the label to something, then change it with a fade, then change it back 
self.myLabel.text = @"text"; 
[self performSelector:@selector(changeLabelText:) withObject:@"hola!" afterDelay:4]; 
[self performSelector:@selector(changeLabelText:) withObject:@"text" afterDelay:8]; 

你也嵌套調用完成塊(並添加延遲PARAM)做不執行類似的東西。爲了進行交叉淡入淡出,應用一種類似的技巧,使用兩個標籤(具有相同的框架),其中一個的alpha值爲零,另一個的alpha值爲1。

+0

這會導致整個'UILabel'漸變,而淡入淡出動畫只會動畫文本,這正是我想要的。 – bdv 2014-11-02 21:38:28

+0

你是說你需要我解釋如何做一個淡入淡出? – danh 2014-11-03 03:41:04