今是昨非

今是昨非

日出江花红胜火,春来江水绿如蓝

CABasicAnimation does not take effect when returning from the secondary interface.

Background#

I discovered that a certain animation in a screen created by a former colleague was initially working, but when returning from a secondary screen, the animation was no longer present. The animation was implemented using CABasicAnimation and added to a layer.

Solution#

Upon inspecting the code, there didn't seem to be any issues since the animation worked the first time. I thought maybe something was happening when the page disappeared, but after investigating, I found that there were no operations performed when the page disappeared.

Looking back at the code, the animation part was implemented in the didMoveToWindow method, as shown below:

The didMoveToWindow method is called when the page appears and disappears. Could it be that adding the animation multiple times caused it to stop working? After modifying the code to only add the animation once, I found that the effect was the same - the animation stopped working when returning from a secondary page.


   override func didMoveToWindow() {
        layer.addSublayer(gradientLayer)
        let basicAnim = CABasicAnimation(keyPath: "animateLocation")
        basicAnim.fromValue = [xxx]
        basicAnim.toValue = [xxx]
        basicAnim.duration = xxx
        basicAnim.repeatCount = Float.infinity
        gradientLayer.add(basicAnim, forKey: nil)
    }

Upon revisiting the code, there didn't seem to be any issues with the implementation, except for the last line where the key was set to nil. Could this be the reason for the problem?

By setting forKey: "basicAnim" and checking the effect, I found that the issue was resolved. Although I checked the documentation and confirmed that key can indeed be set to nil, personally, I usually set it to nil for simplicity when there is only one animation. I only assign a value to key when there are multiple animations. It seems that there are always consequences for taking shortcuts...

The final working code is as follows:

override func didMoveToWindow() {
        layer.addSublayer(gradientLayer)
        let basicAnim = CABasicAnimation(keyPath: "animateLocation")
        basicAnim.fromValue = [xxx]
        basicAnim.toValue = [xxx]
        basicAnim.duration = xxx
        basicAnim.repeatCount = Float.infinity
        gradientLayer.add(basicAnim, forKey: "basicAnim")
}

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.