2012-03-07 109 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;