UITextField边框动画

时间:2012-03-07 11:56:30

标签: objective-c ios uitextfield uicolor

我正在尝试为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添加了红色边框,但没有动画。

2 个答案:

答案 0 :(得分: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;
    

答案 1 :(得分:0)

这些属性不可动画。 Yu需要删除文本字段边框,并在文本字段后面创建一些带有所需边框的UIView。同时将其alpha属性设置为0.0,并在需要时将其设置为1.0。 (alpha属性是可动画的,所以这将为你工作)。

EDIT。

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;
}];