LoginSignup
3
2

More than 5 years have passed since last update.

UITextFieldのスタイルがRoundedRectの場合、背景色が変わらない(Core Animation)

Last updated at Posted at 2015-12-31

問題

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を透明にすることで、背景色が変わる。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2