2012-03-07 103 views
3

我試圖給UITextField邊框顏色設置動畫(淡入)。這是我嘗試的UITextField邊框動畫

tmp.layer.borderColor= [UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.0].CGColor; 
tmp.layer.borderWidth = 1.0f; 

[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration:2]; 
tmp.layer.borderColor= [UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:1.0].CGColor; 
[UIView commitAnimations]; 

上面的代碼將紅色邊框添加到textFields,但沒有動畫。

回答

0

這些屬性不具動畫性。你需要刪除你的文本字段邊框,並在你的文本字段後面用你想要的邊框創建一些其他的UIView。還可以將它的alpha屬性設置爲0.0,並在需要時將其設置爲1.0。 (alpha屬性是動畫的,所以這會爲你做的工作)。

編輯。

tmp.layer.borderColor= [UIColor redColor].CGColor; 
tmp.layer.borderWidth = 1.0f; 
tmp.alpha = 0.0; 
//somewhere here should be the [someView addSubview:tmp]; 
//and after that should go the [someView addSubview:yourTextFieldView]; 

//somewhere later in your code, when you need the animation to happen 
[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration:2]; 
tmp.alpha = 1.0; 
[UIView commitAnimations]; 

您也可以使用所謂的一個階段的動畫像這樣:

[UIView animateWithDuration:2.0 animations:^{ 
    tmp.alpha = 1.0; 
}]; 
+0

請參閱更新的代碼。 Alpha通道仍然不動畫。 – foho 2012-03-07 12:19:42

+0

不,請設置不帶alpha的顏色。我的意思是視圖本身的alpha屬性應該是動畫的。像'tmp.alpha = 0.0;'在創建階段,'tmp.alpha = 1.0;'在動畫塊內部。 – Ariel 2012-03-07 12:27:44

+0

我無法得到它。你能告訴我一個例子嗎? – foho 2012-03-07 12:33:21

2

我遇到了麻煩關於動畫爲UITextField的邊界,所以我想我提供解。我能夠使用CABasicAnimation完成我的任務來執行UITextField動畫。

下面是代碼塊:

textField.layer.borderWidth = 1.0f; 

[CATransaction begin]; { 
    [CATransaction setCompletionBlock:^{ 
     // How the textField should look at the end of the animation. 
     textField.layer.borderColor = [UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:1.0].CGColor; 

    }]; 

    // The keyPath specifies which attribute to modify. In this case it's the layer's borderColor. 
    CABasicAnimation *colorAnimation = [CABasicAnimation animationWithKeyPath:@"borderColor"]; 

    // fromValue provides the beginning state of the animation. 
    colorAnimation.fromValue = (__bridge id)[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0].CGColor; 

    // The to value is the final state of the animation. NOTE: That upon completion of the animation is removed. 
    colorAnimation.toValue = (__bridge id)[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:1.0].CGColor ; 
    color.duration = 2.0; 

    // Finally you add the animation to the textField's layer. 
    [textField.layer addAnimation:colorAnimation forKey:@"color"]; 

} [CATransaction commit]; 

現在動畫僅是在現有的一個臨時施加的層。因此,爲了使動畫永久的最終結果有兩種方法:

  1. 可最後的結果設置爲在CATransaction完成塊的UITextField層。如上面的代碼所示。

  2. 通過將動畫的接收器設置爲在其最終狀態中可見並防止刪除動畫。如下圖所示:

    // Prevents the removal of the final animation state from visibility. 
        // Add these before you add the animation to the textField's layer. 
        colorAnimation.fillMode = kCAFillModeForwards; 
        colorAnimation.removedOnCompletion = false;