CABasicAnimation resets to initial value after animation completes

后端 未结 15 2550
闹比i
闹比i 2020-12-04 05:44

I am rotating a CALayer and trying to stop it at its final position after animation is completed.

But after animation completes it resets to its initial position.

15条回答
  •  佛祖请我去吃肉
    2020-12-04 06:22

    The easiest solution is to use implicit animations. This will handle all of that trouble for you:

    self.layer?.backgroundColor = NSColor.red.cgColor;
    

    If you want to customize e.g. the duration, you can use NSAnimationContext:

        NSAnimationContext.beginGrouping();
        NSAnimationContext.current.duration = 0.5;
        self.layer?.backgroundColor = NSColor.red.cgColor;
        NSAnimationContext.endGrouping();
    

    Note: This is only tested on macOS.

    I initially did not see any animation when doing this. The problem is that the layer of a view-backed layer does not implicit animate. To solve this, make sure you add a layer yourself (before setting the view to layer-backed).

    An example how to do this would be:

    override func awakeFromNib() {
        self.layer = CALayer();
        //self.wantsLayer = true;
    }
    

    Using self.wantsLayer did not make any difference in my testing, but it could have some side effects that I do not know of.

提交回复
热议问题