Animated border button in quick

I recently learned how to animate a button using alpha so that it fades out in Swift. However, if I would like to change only the alpha of the border itself, the animation does not seem to work. Instead, it β€œjumps” from state to state.

UIView.animateWithDuration(1.0, delay: 0.0, options: nil, animations: { var borderColor = UIColor(red: 0.41, green: 1.28, blue: 1.85, alpha: 0.0) self.startButton.layer.borderColor = borderColor.CGColor }, completion: nil); 

The above code, for example, is not animated; instead, it creates a β€œjump” between alpha 1.0 and 0.0 borders.

However, this will work fine (changing the alpha of the whole button):

 UIView.animateWithDuration(1.0, delay: 0.0, options: nil, animations: { self.startButton.alpha = 1; }, completion: nil); 

Is there any way around this problem?

+5
source share
3 answers

Functions such as borderColor and borderWidth are properties of the button layer. This suggests that you should use basic level animation β€” don't view the animation like your code is trying to do β€” to bring these features to life. It works great; in this animation, I demonstrate what happens when you use the kernel animation to animate borderWidth and cornerRadius together:

enter image description here

The borderColor animation will work similarly.

+1
source

Here's a simple solution:

 let borderWidth:CABasicAnimation = CABasicAnimation(keyPath: "borderWidth") borderWidth.fromValue = 0 borderWidth.toValue = 0.9 borderWidth.duration = 0.5 yourView.layer.borderWidth = 0.5 yourView.layer.borderColor = UIColor.whiteColor().CGColor yourView.layer.addAnimation(borderWidth, forKey: "Width") yourView.layer.borderWidth = 0.0 

This works for me.

+7
source

You cannot animate parts of a layer using UIView animation. Also, I don’t think it is possible to animate the alpha value of a border. To achieve a similar effect, you can animate the border width:

I am using this method:

 func animateBorderWidth(view: UIView, from: CGFloat, to: CGFloat, duration: Double) { let animation:CABasicAnimation = CABasicAnimation(keyPath: "borderWidth") animation.fromValue = from animation.toValue = to animation.duration = duration view.layer.add(animation, forKey: "Width") view.layer.borderWidth = to } 

and then display the border of your view using:

 animateBorderWidth(view: startButton, from: 0, to: 1, duration: 0.3) 

and hide it using:

 animateBorderWidth(view: startButton, from: 1, to: 0, duration: 0.3) 
+3
source

All Articles