問題
CoreAnimationを用いてUITextFieldのlayerの背景色を徐々に変えたい場合に、UITextFieldのborderStyleがRoundedRectの場合うまくいかない。
Core Animationを用いた例
CABasicAnimationを用いて、UITextFieldの背景色を2秒かけてclearColorからblackColorにアニメーションさせている。
Swift
func animateBackgroundColor(textField: UITextField) {
let backgroundColorAnimation: CABasicAnimation = CABasicAnimation(keyPath: "backgroundColor")
backgroundColorAnimation.fromValue = UIColor.clearColor().CGColor
backgroundColorAnimation.toValue = UIColor.blackColor().CGColor
backgroundColorAnimation.duration = 2.0
textField.layer.addAnimation(backgroundColorAnimation, forKey: "BackgroundColor")
}
Objective-C
- (void)animateBackgroundColor:(UITextField *)textField {
CABasicAnimation *backgroundColorAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
backgroundColorAnimation.fromValue = [UIColor clearColor];
backgroundColorAnimation.toValue = [UIColor blackColor];
backgroundColorAnimation.duration = 2.0f;
[textField.layer addAnimation:backgroundColorAnimation forKey:@"BackgroundColor"];
}
解決策
Swift
textField.backgroundColor = UIColor.clearColor()
Objective-C
textField.backgroundColor = [UIColor clearColor];
UITextFieldのbackgroundColorを透明にすることで、背景色が変わる。