objective-c - UITextField 边框动画

标签 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];

上面的代码向文本字段添加了红色边框,但没有动画。

最佳答案

我在为 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 完成 block 中的 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;
    

关于objective-c - UITextField 边框动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9601067/

相关文章:

ios - 在我们的 Swift 文件中,我在哪里导入 swift 模块?

ios - 为什么我的应用会对模态视图外的点击使用react?

ios - 将2个数组组合成字典

ios - 限制用户只能输入七个逗号分隔的单词

ios - 用全新的 Swift 应用程序替换 Objective-C iOS 应用程序,同时保留来自 NSUserDefaults 的值

objective-c - 是否可以从 NSData 或其他图像类型(CFImageRef、CIImage、UIImage)创建 ALAsset 对象?

iphone - 在进入后台和在前台检索时将 NSTimer 的时间保存到磁盘

iphone - editButtonItem 设置但没有减号按钮?

swift - 没有使用 Objective-C 选择器声明用于通知 UIKeyboardWillShowNotification 和 UIKeyboardWillHideNotification 的方法

ios - BOOL 方法有问题