I am removing a NSView with animation from view but when the animation finished the blueView appear and then got removed, which makes a bad animation after I did the fade out, here is what I am using:
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
let blueView: NSView = NSView()
blueView.wantsLayer = true
blueView.layer?.backgroundColor = NSColor.blue.cgColor
self.view.wantsLayer = true
self.view.addSubview(blueView)
blueView.translatesAutoresizingMaskIntoConstraints = false
blueView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
blueView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
blueView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
blueView.heightAnchor.constraint(equalTo: self.view.heightAnchor).isActive = true
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(1000)) {
blueView.fadeAnimation(callBack: { print("Done!"); blueView.alphaValue = 0.0; blueView.removeFromSuperview() })
}
}
}
extension NSView {
func fadeAnimation(callBack: @escaping () -> Void) {
let animation = CABasicAnimation()
animation.delegate = CustomCAAnimationDelegate(callBack: callBack)
animation.keyPath = "opacity"
animation.duration = 2.0
animation.fromValue = 1.0
animation.toValue = 0.0
animation.timingFunction = CAMediaTimingFunction(name: .linear)
self.layer?.add(animation, forKey: nil)
}
}
class CustomCAAnimationDelegate: NSObject, CAAnimationDelegate {
var callBack: () -> Void
init(callBack: @escaping () -> Void) {
self.callBack = callBack
}
internal func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
callBack()
}
}
the goal of this question is removing the view after the fade out animation because there is no need for that also as you can see the used animation is type CABasicAnimation.