今是昨非

今是昨非

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

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

Background#

I found that a certain interface written by a former colleague had an animation effect. Initially, it worked when entering the interface, but when returning from a secondary interface, the animation was no longer present. The animation was implemented using CABasicAnimation and added to the layer.

Solution#

There didn't seem to be any issues with the code, considering that it worked the first time. I thought maybe something was happening when the page disappeared, so I checked and found that there were no operations performed when the page disappeared.

Looking back at the code, the animation part was implemented in didMoveToWindow, 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 changing it to only add the animation once, the effect was the same, but it didn't work 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)
    }

Looking back at the code, there didn't seem to be any issues with the implementation, except for the last line where key was set to nil. Could this be the reason it wasn't working?

By setting forKey: "basicAnim" and checking the effect again, the problem 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's only one animation, and only assign a value to key when there are multiple animations. It seems that you always have to pay your debts when you're in this line of work...

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.