2013-06-28 27 views
10

現在我有一個按鈕的IBAction,它會生成一個隨機數,每個數字都分配給UILabel中的文本。我希望文字淡入,或者其他有趣的動畫也會很酷。有誰知道一個簡單的方法來做到這一點?我如何讓文字淡入UILabel?

現在,我只是用

labelMain.text = @"my text"; 

回答

27

下面的代碼會給你的衰落在標籤上的效果。

- (IBAction)buttonClicked:(UIButton *)sender 
    { 
    labelMain.alpha = 0; 

    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseIn 
    animations:^{ labelMain.alpha = 1;} 
    completion:nil]; 
} 
+0

非常感謝!這是第一次,它像一個魅力工作!非常簡單和容易調整持續時間並添加延遲! – Herbie999

+0

樂意幫忙:) @ Herbie999 –

1

試試這個:

[labelMain setAlpha:0]; 
[UIView beginAnimations:nil context:NULL]; 
[UIView setAnimationDuration:0.8]; 
[labelMain setAlpha:1]; 
[UIView commitAnimations]; 

更改時間是很簡單 - 只需調整代碼值0.8

+2

塊更強大。您應該考慮放棄animateWithDuration的beginAnimations。 – rdurand

6
label.text = @"old text"; 
    [UIView animateWithDuration:0.4 animations:^{ 
     label.alpha = 0.0f; 
    } completion:^(BOOL finished) { 
     label.text = @"next text"; 
     [UIView animateWithDuration:0.4 animations:^{ 
      label.alpha = 1.0f; 
     } completion:^(BOOL finished) { 
      NSLog(@"finished transition"); 
     }]; 
    }]; 
0
// fade out the current value 
[UIView animateWithDuration:0.2 
         delay:0 
        options:0 
       animations:^{ 
        labelMain.alpha = 0.0f; 
       } 
       completion:^(BOOL finished) { 
        // set the new value and fade in 
        labelMain.text = newValue; 
        [UIView animateWithDuration:0.2 
             delay:0 
             options:0 
            animations:^{ 
             labelMain.alpha = 1.0f; 
            } 
            completion:nil]; 

       }]; 
0

這看起來像淡入淡出動畫

[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut 
     animations:^{ 
    labelMain.alpha = 0; 

     [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseIn 
     animations:^{ labelMain.alpha = 1;} 
     completion:nil]; 

    } completion:nil]; 
26

我知道這是一個有點陳舊(11個月),但我認爲這是值得一提的張貼的其他方法替代,我覺得這是一個更好的解決方案。

利用UIView transitionWithView:duration:options:animations:completion類級別的方法的,就像這樣:

NSTimeInterval duration = 0.5f; 
[UIView transitionWithView:labelMain 
        duration:duration 
        options:UIViewAnimationOptionTransitionCrossDissolve 
       animations:^{ 
        labelMain.text = @"new value"; 
       } completion:nil]; 

這將交叉淡入淡出從labelMain.text爲「新價值」的前值。

此方法也適用於其他視圖值,例如,更改UIImageView的圖像。

請參閱Apple's docs的主題。

+1

只要提示,以防萬一任何人想要在同一個超級視圖中動畫大量標籤,只需在'transitionWithView'參數中使用您的超級視圖即可。 –

+2

這是做到這一點的最佳方式。不知道爲什麼這不是被接受的答案。 –