Swift UIView Animation Example

This example will show you how to implement animation for the UIView object in swift. It will tell you how to implement the below three swift UIView animations.

  1. The first uiview animation moves a red view from the screen top left to the bottom right use swift code. It is a spring animation.
  2. The second uiview animation moves from left to right use swift code.
  3. The third uiview animation moves the UIView object from bottom to top.


The swift UIView’s animate method provides animation effect for your UIView instance, what you need to do is just pass different parameters to the function. The parameters contain animation duration seconds, delay seconds, spring animation damping ratio, spring animation initialize velocity, animation effect options (  define animation effect type such as ease-in, ease-out, liner… ), an animation progress closure ( define UIView object’s target properties when the animation stop ) and an animation complete closure ( define the UIView object’s state properties after the animation complete ).

1. Swift UIView Animation Demo.

  1. When the app starts, it will display a red view at the top left of the screen.
  2. There are three buttons located at the screen bottom.
  3. When you click the first button ( button text is Start A UIView Animation Repeatedly With Delay ), it will move the red view from the original position to the target position with a spring animation ( you can see the demo video on youtube https://youtu.be/B4YMHpsoHdM ), you can set different spring animation attributes to make the spring animation behave differently.
  4. The second button ( button text is Left To Right UIView Animation ) implements a uiview animation move from left to right with swift code. When you click the second button, the red uiview object will first move to the screen left side, then it will move from left to right smoothly. You can see the effect on youtube https://youtu.be/ASXHeVXOv7I.
  5. The third button ( button text is Bottom To Top UIView Animation ) implements a uiview animation from bottom to top in swift code. When you click the third button, it will first move the view to the bottom, then move the view object to the screen top with animation. You can see the animation on the youtube video https://youtu.be/Cv_1yEd9FD8.

2. Swift UIView Animation Example Source Files.

Below are the steps to create this example.

  1. Create an Xcode project named with SwiftUIViewAnimationExample, please read the article How To Create A Swift Project In Xcode.
  2. Then click the Main.storyboard file and open the UI controls library dialog and add three buttons to the storyboard. You can read the article How To Display Xcode Library, Assistant Editor, Inspectors Window to learn more.
  3. Now you should add 3 outlet variables and action functions to process the button’s touch inside up event. You can read the article How To Connect Storyboard UI Component To ViewController Class Code.
  4. Each button reference one outlet variable and one action event process function.
  5. Now click to edit ViewController.swift file, and add below swift source code in it.
    //
    //  ViewController.swift
    //  SwiftUIViewAnimationExample
    //
    
    import UIKit
    
    class ViewController: UIViewController {
        
        // Reference the 'Start A UIView Animation Repeatedly With Delay' button.
        @IBOutlet weak var animationButton: UIButton!
        
        // Reference the 'Left To Right UIView Animation' button.
        @IBOutlet weak var leftToRightButton: UIButton!
        
        // Reference the 'Bottom To Top UIView Animation' button.
        @IBOutlet weak var bottomToTopButton: UIButton!
        
        // This structure will be used to represent one UIView's properties include position, size and color.
        struct UIViewAttribute {
            var x:Float
            var y:Float
            var width:Float
            var height:Float
            var color:UIColor
        }
        
        // Get screen width.
        let screenWidth = UIScreen.main.bounds.width
        
        // Get screen height.
        let screenHeight = UIScreen.main.bounds.height
        
        // This is the initialize red view's properties.
        let initialUIViewAttribute : UIViewAttribute = UIViewAttribute(x:10, y:10, width: 100, height: 100, color: UIColor.red)
        
        // Initialize an empty UIView object.
        var redView : UIView = UIView()
        
        // This function will set the button to rouded border button.
        func initializeButton(button:UIButton){
            // Clear button background color.
            button.backgroundColor = UIColor.clear
            
            button.setTitleColor(UIColor.red, for: UIControl.State.focused)
            
            // Set button rounded corner radius.
            button.layer.cornerRadius = 15
            
            // Set button border width.
            button.layer.borderWidth = 5
            
            // Set button border color to green.
            button.layer.borderColor = UIColor.green.cgColor
        }
        
        // This function will be invoked when the app start to render the screen.
        override func viewDidLoad() {
            super.viewDidLoad()
            
            // Create red view object with initialize prarmeters.
            let viewRectFrame = CGRect(x:CGFloat(initialUIViewAttribute.x), y:CGFloat(initialUIViewAttribute.y), width:CGFloat(initialUIViewAttribute.width), height:CGFloat(initialUIViewAttribute.height))
            redView = UIView(frame:viewRectFrame)
            redView.backgroundColor = UIColor.red
            
            // Add the red view to the main screen.
            self.view.addSubview(redView)
            
            // Initialize thre buttons.
            initializeButton(button: self.animationButton)
            initializeButton(button: self.leftToRightButton)
            initializeButton(button: self.bottomToTopButton)
        }
        
        /* When click the first button, this function will be treggered. */
        @IBAction func startUIViewAnimation(_ sender: UIButton) {
            
            // Create target view properties when the animation complete.
            let endUIViewAttribute : UIViewAttribute = UIViewAttribute(x:100, y:250, width: 300, height: 600, color: UIColor.green)
            
            self.animationUIView(endUIViewAttribute: endUIViewAttribute, centerUIView: true, durationSeconds: 5, delaySeconds: 1, usingSpringWithDamping: 0.1, initialSpringVelocity: 1)
            
        }
        
        /* This function will be involed when user click the 'Left To Right UIView Animation' button. */
        @IBAction func leftToRightAnimation(_ sender: UIButton) {
        
            // First move the redView to screen left side.
            var endUIViewAttribute : UIViewAttribute = UIViewAttribute(x:10, y:250, width: 100, height: 100, color: UIColor.red)
            self.animationUIView(endUIViewAttribute: endUIViewAttribute, centerUIView: false, durationSeconds: 2, delaySeconds: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.5)
            
            // Now move the view from creen left to right.
            endUIViewAttribute = UIViewAttribute(x:Float(screenWidth), y:250, width: 100, height: 100, color: UIColor.red)
            self.animationUIView(endUIViewAttribute: endUIViewAttribute, centerUIView: false, durationSeconds: 5, delaySeconds: 1, usingSpringWithDamping: 1, initialSpringVelocity: 1)
        }
        
        /* This method will be called when user click 'Bottom To Top UIView Animation' button. */
        @IBAction func bottomToTopAnimation(_ sender: UIButton) {
            
            // First move the redView to screen bottom.
            var endUIViewAttribute : UIViewAttribute = UIViewAttribute(x:10, y:Float(screenHeight), width: 100, height: 100, color: UIColor.red)
            self.animationUIView(endUIViewAttribute: endUIViewAttribute, centerUIView: false, durationSeconds: 2, delaySeconds: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.5)
            
            // Then move the view object from bottom to top.
            endUIViewAttribute = UIViewAttribute(x:Float(screenWidth), y:10, width: 100, height: 100, color: UIColor.red)
            self.animationUIView(endUIViewAttribute: endUIViewAttribute, centerUIView: false, durationSeconds: 5, delaySeconds: 1, usingSpringWithDamping: 1, initialSpringVelocity: 1)
            
        }
        
        /*
         This function will implement animation for UIView objects.
         */
        func animationUIView(endUIViewAttribute: UIViewAttribute, centerUIView : Bool, durationSeconds:Float, delaySeconds:Float, usingSpringWithDamping: Float, initialSpringVelocity: Float) -> Void{
            
            // Define a swift closure type.
            typealias animationClosure = () -> Void
            
            // Declare an object of above swift closure type.
            let animationClosureVar : animationClosure
            
            // Implement the closure execution code, then animation will trasform the UIView object form original state to the UIView state defined in this closure.
            animationClosureVar = {
                
                () -> Void in
                
                print("Run animationClosure. ")
                
                // Get UIView object properties when the animation stop.
                let endX = endUIViewAttribute.x
                
                let endY = endUIViewAttribute.y
                
                let endWidth = endUIViewAttribute.width
                
                let endHeight = endUIViewAttribute.height
                
                // Set the UIView object target properties.
                self.redView.frame = CGRect(x:CGFloat(endX), y:CGFloat(endY), width:CGFloat(endWidth), height:CGFloat(endHeight))
                // Set the UIView object's color to green.
                self.redView.backgroundColor = UIColor.green
                
            }
            
            // Define a closure type when the animation complete.
            typealias animationCompletionClosure = (_ finished : Bool) -> Void
            // Implement above closure type.
            let animationCompletionClosureVar : animationCompletionClosure = {
                
                (finished) -> Void in
                
                print("Run animationCompletionClosure. ")
                
                // When the animation complete, if centerUIView parameter's value is true then center the UIView object.
                if(centerUIView){
                    // get screen size object.
                    let screenSize: CGRect = UIScreen.main.bounds
                    
                    // get screen width.
                    let screenWidth = screenSize.width
                    
                    // get screen height.
                    let screenHeight = screenSize.height
                    
                    self.redView.center = CGPoint(x: screenWidth/2, y: screenHeight/2)
                    
                    self.redView.backgroundColor = UIColor.red
                }
            }
            
            
            //UIView.animate(withDuration: 10, animations: animationClosureVar, completion: animationCompletionClosureVar)
            
            // Call the UIView.animate function to implement the animation.
            UIView.animate(withDuration: TimeInterval(durationSeconds), delay: TimeInterval(delaySeconds), usingSpringWithDamping: CGFloat(usingSpringWithDamping), initialSpringVelocity: CGFloat(initialSpringVelocity), options: UIView.AnimationOptions.curveEaseInOut, animations: animationClosureVar, completion: animationCompletionClosureVar)
        }
    }

References

  1. Apple’s UIView animate function document

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.