I have a code-created button. Every time I click, I want it to perform CABasicAnimation before removeFromSuperView(). But if I add removeFromSuperView() after that, it will instantly removeFromSuperView() without any animation.
@objc func bubblePressed(_ bubble:Bubble){
let animation = CABasicAnimation(keyPath:"opacity")
animation.fromValue = 1
animation.toValue = 0
animation.duration = 2.0
bubble.layer.add(animation, forKey:nil)
bubble.removeFromSuperview()
}
Is there any way that I can achieve this?
@objc func bubblePressed(_ bubble:Bubble){
CATransaction.begin()
CATransaction.setCompletionBlock({
// remove from super view
bubble.removeFromSuperview()
})
let animation = CABasicAnimation(keyPath:"opacity")
animation.fromValue = 1
animation.toValue = 0
animation.duration = 2.0
bubble.layer.add(animation, forKey:nil)
CATransaction.commit()
}
Workaround 2
@objc func bubblePressed(_ bubble:Bubble){
let animation = CABasicAnimation(keyPath:"opacity")
animation.fromValue = 1
animation.toValue = 0
animation.duration = 2.0
animatio.delegate = self
bubble.layer.add(animation, forKey:nil)
}
extension ViewController: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
bubble.removeFromSuperview()
// remove from super view in this function .. its Delegate method
}
}