現在我有一個按鈕的IBAction,它會生成一個隨機數,每個數字都分配給UILabel中的文本。我希望文字淡入,或者其他有趣的動畫也會很酷。有誰知道一個簡單的方法來做到這一點?我如何讓文字淡入UILabel?
現在,我只是用
labelMain.text = @"my text";
現在我有一個按鈕的IBAction,它會生成一個隨機數,每個數字都分配給UILabel中的文本。我希望文字淡入,或者其他有趣的動畫也會很酷。有誰知道一個簡單的方法來做到這一點?我如何讓文字淡入UILabel?
現在,我只是用
labelMain.text = @"my text";
下面的代碼會給你的衰落在標籤上的效果。
- (IBAction)buttonClicked:(UIButton *)sender
{
labelMain.alpha = 0;
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseIn
animations:^{ labelMain.alpha = 1;}
completion:nil];
}
試試這個:
[labelMain setAlpha:0];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.8];
[labelMain setAlpha:1];
[UIView commitAnimations];
更改時間是很簡單 - 只需調整代碼值0.8
。
塊更強大。您應該考慮放棄animateWithDuration的beginAnimations。 – rdurand
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");
}];
}];
// 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];
}];
這看起來像淡入淡出動畫
[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];
我知道這是一個有點陳舊(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的主題。
只要提示,以防萬一任何人想要在同一個超級視圖中動畫大量標籤,只需在'transitionWithView'參數中使用您的超級視圖即可。 –
這是做到這一點的最佳方式。不知道爲什麼這不是被接受的答案。 –
非常感謝!這是第一次,它像一個魅力工作!非常簡單和容易調整持續時間並添加延遲! – Herbie999
樂意幫忙:) @ Herbie999 –