summary
To implement a set of repeated animations, it is essentially to find the starting point and end point of the animation. At the end of the animation, trigger the start point and continue this action.
The logic to be sorted out here is 1. Triggering the start point and 2. Monitoring the end point of the animation. These two logics are the basis for implementing repeated animations.
Application scenarios
Set UI controls such as imageView into a panning animation and keep in the animation.
transform can implement the translation of controls, but cannot be continuously animation.
API and language
Core logic/code
transform can translate controls, and in order to achieve continuous animation, it can be implemented recursively.
Animation implementation
Set up the animation and start
Animate the (withDuration: , animations: , completion: ) function.
This method includes the start animation event and the monitoring animation completion event (completeion method)
Implement continuous animation
Recursively call the start animation function in completion to achieve the effect of continuous animation.
Stop animation
Set a global flag to record the state of the animation. You can also change this state to determine whether you need to start the animation, such as setting the isHidden property of the UI control to achieve stopping the animation
detail
When starting the animation, make a judgment. If isHidden is true, stop the animation directly. You can accurately control the number of animations.
Setting a closure in the start animation function, you can set code to stop animation in the closure, etc.
Sample code
Repeat the pan-moving artwork 3 times, and judge before each animation starts. During the animation process, if you want to stop the animation, just set = false and stop the animation.
func guideAnimations() { // The animation is executed 3 times var count = 3 // Start animation startAnimation {[weak self] in guard let self = self else { return } count -= 1 if count == 0 { = true } } } // Set and start animation func startAnimation(_ complete: @escaping ()->()) { if { return } (withDuration: 1, delay: 0, options: .curveEaseInOut) { = (x: -50, y: 0) } completion: { [weak self](finish) in // Restore the control when the animation ends guard let self = self else { return } = (x: 50, y: 0) // Return the closure first, and then execute the animation function complete() (complete) } } // Stop animation func stopAnimation() { if == false { = true } }
This is the article about Swift’s use of transform to achieve the effect of repeated flat painting. For more related transform, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!