0

I would like animate the width and alpha of my UIButton's titleLabel. The alpha animation should start after 1 second.
I'm trying to do it with Core Animation:

    let animSize = CAKeyframeAnimation(keyPath: "bounds")
    animSize.values = [btn1.layer.frame,CGRect(origin: btn1.layer.frame.origin, size: CGSize(width: 300, height: btn1.layer.frame.height))]
    animSize.duration = 3
    animSize.isRemovedOnCompletion = false
    animSize.fillMode = kCAFillModeForwards
    btn1.layer.add(animSize, forKey: "bounds")

    let animAlpha = CABasicAnimation(keyPath: "opacity")
    animAlpha.fromValue = 0.0
    animAlpha.toValue = 1.0
    animAlpha.timeOffset = 1.0
    animAlpha.isRemovedOnCompletion = false
    animAlpha.fillMode = kCAFillModeForwards
    btn1.titleLabel?.layer.add(animAlpha, forKey: "opacity")

When I run the animations separately, everything's working, but when I run them together, only the first animation ("bounds") is evaluating. I know I can do it with UIView.animate but in that case I will lose the "delay" option. I've also tried to put those animations in a CAAnimationGroup but nothing changed. I want to run those animations simultaneously therefore I can't use a completion block.

Thank you for any advice.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
adam_
  • 25
  • 2

2 Answers2

0

You won't lose the "delay" option with UIView.animate. You can use two animation blocks to achieve the same result:

UIView.animate(withDuration: 3) {
    btn1.frame = CGRect(origin: btn1.frame.origin, size: CGSize(width: 300, height: btn1.frame.height))
}

UIView.animate(withDuration: 2, delay: 1, options: [], animations: {
    btn1.alpha = 1
}, completion: nil)
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
0

You may also try it with autolayout by hooking the button's width constraint as IBOutlet

 btn1.withCon.constant = 300 
 UIView.animate(withDuration: 3) {
    self.view.layoutIfNeeded()
}

UIView.animate(withDuration: 2, delay: 1, options: [], animations: {
    btn1.alpha = 1
}, completion: nil)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87