2015-02-06 35 views
0

我想通過使用animateWithDuration淡出標籤的背景顏色,但是我的代碼沒有解決。下面是我有:如何使用animateWithDuration淡出標籤的背景顏色

.H(在@interface ...)

IBOutlet UILabel *labelColor; 

.M(在viewDidLoad方法)

[labelColor setBackgroundColor:[UIColor colorWithRed:55/255.0 green:191/255.0 blue:122/255.0 alpha:0.3]]; 

if (labelColor.alpha >= 0.3) { 
    [UIView animateWithDuration:1 animations:^{ 
     labelColor.alpha = 0.3; 
     labelColor.alpha = 1.0; 
    }]; 
} else if (labelColor.alpha == 1.0) { 
    labelColor.alpha = 0.3; 
} 

色0.3阿爾法顯示出來,但不會從0.3降到1.0。我試圖做到這一點,因此標籤的顏色在連續循環中從0.3降低到1.0,在alpha達到1.0時將alpha重置爲0.3。

任何有關如何實現這一點的幫助表示讚賞。

+0

您當前的代碼沒有多大意義了很多原因,但你想淡出整個標籤還是隻背景? – 2015-02-06 20:35:53

+0

你提到你想要淡化到「循環」......循環在你的代碼中扮演什麼角色? – 2015-02-06 20:36:50

+0

整個標籤,因爲不會有文字。我的印象是,我的if/else語句會按照我設置的方式創建某種循環。我也在玩使用int變量來保存0.3和1.0的值,而不是使用labelColor.alpha,但仍然沒有弄明白。 – user3781632 2015-02-06 20:52:20

回答

0

你應該設置你的初始條件以外的動畫塊的

labelColor.alpha = 0.3; 
[UIView animateWithDuration:1 animations:^{ 
    labelColor.alpha = 1.0; 
}]; 

旁註:這會減弱整個UILabel的Alpha值,而不只是背景色。如果你想要的文字留下來,而你的背景消失,你應該使用的東西沿着這些線路更多:

labelColor.backgroundColor = [UIColor colorWithRed:55/255.0 green:191/255.0 blue:122/255.0 alpha:0.3]; 
[UIView animateWithDuration:1 animations:^{ 
    labelColor.backgroundColor = [UIColor colorWithRed:55/255.0 green:191/255.0 blue:122/255.0 alpha:1.0]; 
}]; 
1

有與您當前密碼的幾個問題:

(1)您else語句將永遠不會被稱爲因爲如果labelColor.alpha == 1.0也將是> = 0.3

(2)具有的動畫塊中既labelColor.alpha = 0.3;labelColor.alpha = 1.0;意味着只有第二行(即labelColor.alpha = 1.0;)將決定動畫

(3)您沒有設置一個循環,只要你願意

(4)您沒有動畫淡出

如果我其實理解它是你在做什麼試圖完成的任務,你可以不斷進出,像這樣淡出整個UILabel

- (void)performLabelFade { 
    // If the label is faded out, fade it in 
    if (labelColor.alpha == .3) { 
     [UIView animateWithDuration:1 animations:^{ 
      labelColor.alpha = 1.0; 
     } completion:^(BOOL finished) { 
      // Repeat the current method (i.e. like a loop) 
      [self performLabelFade]; 
     } 
    } 
    // Else if the label is faded in, fade it out 
    else if (labelColor.alpha == 1.0) { 
     [UIView animateWithDuration:1 animations:^{ 
      labelColor.alpha = 0.3; 
     } completion:^(BOOL finished) { 
      // Repeat the current method (i.e. like a loop) 
      [self performLabelFade]; 
     } 
    } 
} 
+0

謝謝你的寫作,我會測試一下。我設法弄清楚了使用上面提到的NSTimer設置它的另一種方法。再次感謝您的幫助! (因爲我的代表低,所以不能升職。= /) – user3781632 2015-02-06 21:56:29