Henrik
Henrik

Reputation: 4044

CABasicAnimation too verbose

In my application I have several fades. I create them with Core Animation, using syntax similar to what is below. Is there a less verbose syntax I could use?

  CATransaction.begin()
  let fade = CABasicAnimation(keyPath: "opacity")
  fade.fromValue = 0
  fade.toValue = 1
  fade.duration = 0.35
  fade.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
  fade.fillMode = kCAFillModeForwards
  fade.removedOnCompletion = false

  CATransaction.setCompletionBlock({
      ...
  })

  self.addAnimation(fade, forKey: nil)
  CATransaction.commit()

Upvotes: 0

Views: 190

Answers (2)

Duncan C
Duncan C

Reputation: 131491

As an alternative to @jtbandes' excellent answer (voted), in many cases you can use a much simpler UIView animation:

UIView.animateWidhDuration(.35
animations:
{
  myView.alpha = 0
}
completion:
{
  (finshed) in
  //your completion code here
})

EDIT:

I see from your comment that you're developing for OS X. That requires a different technique, using the animation proxy for your view:

myView.animator.setAlphaValue(0.0)

And if you want it to use a different duration than the default 0.25 second duration, you need to set that in an animation context group:

NSAnimationContext.currentContext().beginGrouping()
NSAnimationContext.currentContext().setDuration(0.35)
myView.animator.setAlphaValue(0.0)
NSAnimationContext.currentContext().endGrouping()

I believe that unlike iOS, NSViews don't have a native alpha setting, and setAlphaValue actually manipulates the alpha value of the view's layer. In that case you will probably need to set the view as layer-backed.

Upvotes: 1

jtbandes
jtbandes

Reputation: 118761

Sure. You can make your own:

extension CABasicAnimation
{
    convenience init(_ keyPath: String, from: AnyObject?, to: AnyObject?, duration: CFTimeInterval = 0.3)
    {
        self.init(keyPath: keyPath)
        fromValue = from
        toValue = to
        self.duration = duration
    }
}

extension CALayer
{
    func addAnimation(animation: CAAnimation, forKey key: String?, completion: Void -> Void)
    {
        CATransaction.begin()
        CATransaction.setCompletionBlock(completion)
        addAnimation(animation, forKey: key)
        CATransaction.commit()
    }
}

// later...

let fade = CABasicAnimation("opacity", from: 0, to: 1, duration: 0.35)
self.addAnimation(fade, forKey: nil) {
    // ...
}

Upvotes: 2

Related Questions