我正在尝试为 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];
现在动画只是一个临时叠加在现有动画之上的图层。所以为了让动画的最终结果永久存在有两种方法:
您可以将最终结果设置到 CATransaction 完成 block 中的 UITextField 层。如上面的代码所示。
通过将动画的接收器设置为在其最终状态下可见并防止移除动画。如下所示:
// 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/