CABasicAnimation resets to initial value after animation completes

后端 未结 15 2554
闹比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:05

    Here is a sample from playground:

    import PlaygroundSupport
    import UIKit
    
    let resultRotation = CGFloat.pi / 2
    let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 200.0, height: 300.0))
    view.backgroundColor = .red
    
    //--------------------------------------------------------------------------------
    
    let rotate = CABasicAnimation(keyPath: "transform.rotation.z") // 1
    rotate.fromValue = CGFloat.pi / 3 // 2
    rotate.toValue = resultRotation // 3
    rotate.duration = 5.0 // 4
    rotate.beginTime = CACurrentMediaTime() + 1.0 // 5
    // rotate.isRemovedOnCompletion = false // 6
    rotate.fillMode = .backwards // 7
    
    view.layer.add(rotate, forKey: nil) // 8
    view.layer.setAffineTransform(CGAffineTransform(rotationAngle: resultRotation)) // 9
    
    //--------------------------------------------------------------------------------
    
    PlaygroundPage.current.liveView = view
    
    1. Create an animation model
    2. Set start position of the animation (could be skipped, it depends on your current layer layout)
    3. Set end position of the animation
    4. Set animation duration
    5. Delay animation for a second
    6. Do not set false to isRemovedOnCompletion - let Core Animation clean after the animation is finished
    7. Here is the first part of the trick - you say to Core Animation to place your animation to the start position (you set in step #2) before the animation has even been started - extend it backwards in time
    8. Copy prepared animation object, add it to the layer and start the animation after the delay (you set in step #5)
    9. The second part is to set correct end position of the layer - after the animation is deleted your layer will be shown at the correct place

提交回复
热议问题