Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating button border in swift

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?

like image 624
vanillaboy Avatar asked Apr 03 '15 14:04

vanillaboy


1 Answers

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.

like image 154
Meseery Avatar answered Nov 07 '22 04:11

Meseery