在我的应用程序中,我有几个淡入淡出。我用核心动画创建它们,使用与下面类似的语法。我能用一种不那么冗长的语法吗?

  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()

最佳答案

当然。你可以自己做:

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) {
    // ...
}

关于macos - CABasicAnimation太冗长,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31469646/

10-13 07:34