Reputation: 93
I recently learned how to animate a button using alpha so that it fades in/out in Swift. However, if I would like to only have the alpha of the border itself change, the animation does not seem to be working. 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 does not animate, instead it produces a "jump" between alpha 1.0 and 0.0 of the border.
However, this would work fine (changing the alpha of the entire button):
UIView.animateWithDuration(1.0, delay: 0.0, options: nil, animations: {
self.startButton.alpha = 1;
}, completion: nil);
Is there any way to get around this issue?
Upvotes: 9
Views: 8722
Reputation: 13527
You can't animate parts of the layer
using UIView
animations. Also, I don't think it's possible to animate the alpha value of the border. To achieve a similar effect you can animate the width of your border:
I made this UIView
extension:
extension UIView {
func animateBorderWidth(toValue: CGFloat, duration: Double = 0.3) {
let animation = CABasicAnimation(keyPath: "borderWidth")
animation.fromValue = layer.borderWidth
animation.toValue = toValue
animation.duration = duration
layer.add(animation, forKey: "Width")
layer.borderWidth = toValue
}
}
and then show the border of your view by using:
startButton.animateBorderWidth(toValue: 1, duration: 0.5)
and hide it by using:
startButton.animateBorderWidth(toValue: 0)
Upvotes: 13
Reputation: 1855
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
It works for me.
Upvotes: 13
Reputation: 534925
Features such as the borderColor
and borderWidth
are properties of the button's layer. That tells you that you must use core animation of the layer - not view animation, as your code tries to do - to animate such features. It works perfectly well; in this animation, I demonstrate what happens when you use core animation to animation the borderWidth
and the cornerRadius
together:
Animation of the borderColor
would work similarly.
Upvotes: 4