removeFromSuperView() 之前的 CABasicAnimation 性能

CABasicAnimation performance before removeFromSuperView()

我有一个代码创建的按钮。每次单击时,我都希望它在 removeFromSuperView() 之前执行 CABasicAnimation。但是如果我在那之后添加 removeFromSuperView() ,它会立即 removeFromSuperView() 而没有任何动画。

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

有什么办法可以实现吗?

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

}

解决方法 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
                }
           }