Swift UIView Animation Example

This example will show you how to implement animation for UIView object in swift. It will display three swift UIView animations. The first animation is a spring animation which will move a red view from screen top left to the bottom right. The second animation will show you how to move UIView from left to right. The third animation will show you how to move UIView object from screen bottom to screen top.

The swift UIView’s animate method provide animation effect for your UIView instance, what you need to do is just pass different parameters to the function. The parameters contains 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 etc ), 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 ). You can refer Apple’s UIView animate function document for detail.

1. Swift UIView Animation Demo.

First let us look at the example demo as below. When the app start, it will display a red view at top left of the screen. There are three buttons located at the screen bottom. When you click the first button, it will move the red view from the original position to the target position with a spring animation, you can set different spring animation attributes to make the spring animation act different.

swift uiview animation new

When you click the second button, the red view object will first move to screen left side, then it will move from screen left side to right side smoothly.

swift uiview animation left to right

When you click the third button, it will first move the view to the bottom, then move the view object to screen top with animation.

swift uiview animation bottom to top

2. Swift UIView Animation Example Source Files.

Below is this example project source files list in Xcode. And we will tell you how to create it step by step.

swift uiview animation example source files

  1. First create a Xcode project named with SwiftUIViewAnimationExample, please read article How To Create A Swift Project In Xcode.
  2. Then click the Main.storyboard file and open ui controls library dialog and add three button to the storyboard. You can read article How To Display Xcode Library, Assistant Editor, Inspectors Window to learn more.
  3. Now you should add three button outlet variable and action functions to process the button’s touch inside up event. You can read article How To Connect Storyboard UI Component To ViewController Class Code.
  4. From above picture we can see 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
    //
    //  Created by song zhao on 7/1/19.
    //  Copyright © 2019 dev2qa.com. All rights reserved.
    //
    
    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)
        }
        
        
    
    
    }
    
    
READ :   How To Use Swift Closures Example

Leave a Reply

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.