gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:29:00 26 4
gpt4 key购买 nike

我正在使用 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 执行此操作的等效方法是什么?

最佳答案

我想我知道怎么做了。

下面是一些示例代码,您可以将其粘贴到 Xcode 中的 playground 中:

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 委托(delegate),并且可以覆盖 animationDidStop 以在动画时执行其他任务完成。

关于ios - 有没有办法在 CAKeyframeAnimation 完成动画时调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33901549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com