有没有办法在CAKeyframeAnimation完成动画时调用方法?

时间:2015-11-24 18:51:20

标签: ios swift nsobject caanimation cakeyframeanimation

我正在使用Swift,我需要在CAKeyframeAnimation完成后做一些事情。

如果这是UIView,我通常会使用UIView.animateWithDuration,并且只会在completionHandler中实现这样的内容:

    UIView.animateWithDuration(duration, delay: delay, options: [],
        animations: { },
        completion: {
            (animationFinished: Bool) in

            if animationFinished {
            // DO SOME STUFF IN HERE ONCE THE ANIMATION FINISHES
            }
    })

使用CAKeyframeAnimation执行此操作的等效方法是什么?

2 个答案:

答案 0 :(得分:2)

我想我想出了如何做到这一点。

以下是一些可以粘贴到Xcode中的游乐场的示例代码:

import XCPlayground

class BallAnimation: NSObject { // <- STEP 1 - INHERIT FROM NSOBJECT
  func doMyAnimation() {
    // Make a test background.
    let backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
    XCPlaygroundPage.currentPage.liveView = backgroundView

    // Create the object that will be animated and add it to the background.
    let ballImage = UIImage(named: "ball")
    let ballView = UIImageView(image: ballImage)
    backgroundView.addSubview(ballView)

    // Create the path the object will follow.
    let path = UIBezierPath()
    path.moveToPoint(CGPoint(x: 200, y: 200))
    path.addLineToPoint(CGPoint(x: 200, y:100))

    // Create the animation that will use the path we just created.
    let animation = CAKeyframeAnimation(keyPath: "position")
    animation.path = path.CGPath
    animation.duration = 2.0
    animation.removedOnCompletion = false
    animation.fillMode = kCAFillModeForwards
    animation.delegate = self // <- STEP 2 - SET THE DELEGATE

    // This should start the animation
    ballView.layer.addAnimation(animation, forKey: "animate ball")
  }

  // STEP 3 - OVERRIDE THIS METHOD
  override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
    // When the animation stops it should call this method (make sure the delegate was set above).
    print("Animation did stop.")
  }
}

// Create an instance of the class and call the method that starts the animation.
let ballAnimation = BallAnimation()
ballAnimation.doMyAnimation()

<强>说明

CAAnimation类将以下方法添加到NSObject

func animationDidStop(_ anim: CAAnimation, finished flag: Bool)

因此,如果一个类继承自NSObject,则可以将其设置为CAKeyframeAnimation委托,并且可以覆盖animationDidStop以在动画结束时执行其他任务。

答案 1 :(得分:0)

我在 XCode 12 中做了这样的事情:

&{for summary}    
{IF ${Risk} = "High" ${Summary} { IF ${Risk} = "Critical" ${Summary} }}
&{end}