How To Use iOS Progress View Programmatically In Swift

UIKit.UIProgressView class is used to implement the iOS progress bar component. This article will tell you how to use it both in the Main.storyboard visually and swift source code programmatically. First, let us look at the example video below.

1. Swift Progress View Example Video Demo.

  1. If you can not watch the above video, you can see it on URL https://youtu.be/7K8Zq3DtIwg
  2. There are two buttons and two progress views in this example. The top button and the progress view are added to the Main.storyboard visually. The bottom button and progress view is added in swift source code programmatically.
  3. When the app starts, the progress views are all hidden. When you press one button, the related progress view will be displayed and animated, all the buttons will be disabled. When the progress view animates complete, it will be hidden again, and the buttons will be enabled.

2. Swift Progress View Example Source Code.

  1. Create an Xcode project with the name iOSProgressBarExample ( How To Create A Swift Project In Xcode).
  2. Edit Main.storyboard file in Xcode, add one UIProgressView and one UIButton from UI component library into Main.storyboard View Controller Scene ( How To Display Xcode Library, Assistant Editor, Inspectors Window ).
  3. Add layout constraints ( Progress View1.top = Safe Area.top + 100, Progress View1.centerX = centerX, Btn1.top = Progress View1.bottom + 30, Btn1.centerX = centerX ) to above UIProgressView and UIButton object ( How To Add Constraints In Xcode 10 To Implement Auto Layout ).
    ios-progress-view-example-layout-constraints
  4. Edit the project ViewController.swift file and copy the below source code into it. You can see the code in function initProgressView2Btn2 to learn how to create and use the UIProgressView object programmatically.
    //
    //  ViewController.swift
    //  iOSProgressBarExample
    //
    //  Created by song zhao on 12/24/19.
    //  Copyright © 2019 dev2qa.com. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController {
    
        // Outlet variables reference for ui component UIProgressView and UIButton.
        @IBOutlet weak var progressView1: UIProgressView!
        @IBOutlet weak var btn1: UIButton!
        
        // Cuszomize defined UIProgressView and UIButton object.
        var progressView2: UIProgressView!
        var btn2: UIButton!
        
        // Button tag variable.
        let TAG_1 = 1
        let TAG_2 = 2
        
        // Save current pressed button tag.
        var currentBtnTag = 0
        
        // Timer object which is used to create a timer.
        var timer:Timer? = nil
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            initProgressView1Btn1()
            
            initProgressView2Btn2()
            
        }
        
        // Initialize btn1 and progressView1.
        func initProgressView1Btn1(){
            
            // Set btn1's tag.
            btn1.tag = TAG_1
            
            // Activate progressView1's width layout constraint.
            let widthAnchor = progressView1.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.8, constant: 1)
            widthAnchor.isActive = true
            
            // Hide progressView1 object.
            self.progressView1.isHidden = true
            
        }
        
        // Initialize btn2 and progressView2.
        func initProgressView2Btn2(){
            
            // Create and initialize progressView2 object.
            progressView2 = UIProgressView()
            
            // Hide progressView2 object.
            progressView2.isHidden = true
            
            // Set progressView2's initialize progress value.
            progressView2.progress = 0
            
            // Set translatesAutoresizingMaskIntoConstraints property value to false, so that you can change progressView2's layout constraints in swift source code.
            progressView2.translatesAutoresizingMaskIntoConstraints = false
            
            // Add progressView2 to the app's root view.
            self.view.addSubview(progressView2)
            
            // Change progressView2's centerx, width and top anchor layout.
            let centerXAnchor = progressView2.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
            centerXAnchor.isActive = true
            
            let widthAnchor = progressView2.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.9)
            widthAnchor.isActive = true
            
            let topAnchor = progressView2.topAnchor.constraint(equalTo: self.btn1.bottomAnchor, constant: 100)
            topAnchor.isActive = true
            
            //***************************************************************************
            
            // Create and initialize btn2 object.
            btn2 = UIButton()
            
            // Set btn2's tag.
            btn2.tag = TAG_2
            
            // Set translatesAutoresizingMaskIntoConstraints property value to false, so that you can change btn2's layout constraints in swift source code.
            btn2.translatesAutoresizingMaskIntoConstraints = false
            
            // Set btn2's title, normal state title color and disabled state title color.
            btn2.setTitle("Download", for: UIControl.State.normal)
            
            btn2.setTitleColor(UIColor.red, for: UIControl.State.normal)
            
            btn2.setTitleColor(UIColor.lightGray, for: UIControl.State.disabled)
            
            // Set btn2's font text size.
            btn2.titleLabel?.font = UIFont.systemFont(ofSize: 35)
            
            // Set btn2's background color.
            btn2.backgroundColor = UIColor.green
            
            btn2.layer.cornerRadius = 5
            
            self.view.addSubview(btn2)
            
            let widthAnchor1 = btn2.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.8, constant: 1)
            widthAnchor1.isActive = true
            
            let topAnchor1 = btn2.topAnchor.constraint(equalTo: self.progressView2.bottomAnchor, constant: 100)
            topAnchor1.isActive = true
            
            let centerXAnchor1 = btn2.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
            centerXAnchor1.isActive = true
            
            self.btn2.isEnabled = true
            
            self.btn2.addTarget(self, action: #selector(pressButton), for: UIControl.Event.touchDown)
            
        }
        
    
        // This function will be invoked when press btn1 and btn2.
        @IBAction func pressButton(_ sender: UIButton) {
            
            self.currentBtnTag = sender.tag
            
            btn1.isEnabled = false
            
            btn2.isEnabled = false
            
            if(self.currentBtnTag == btn1.tag)
            {
                self.progressView1.isHidden = false
                
                self.progressView2.isHidden = true
            }else if(self.currentBtnTag == btn2.tag)
            {
                self.progressView1.isHidden = true
                
                self.progressView2.isHidden = false
            }
            
            startTimer()
        
        }
        
        
        /* This function will start a timer object and start the timer. */
        func startTimer() -> Void{
            
            timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(startDownload), userInfo: nil, repeats: true)
           
        }
           
    
        @objc func startDownload(){
            
            if(currentBtnTag == TAG_1){
                
                showProgressView(progressView: self.progressView1)
                
            }else if(currentBtnTag == TAG_2){
                
                showProgressView(progressView: self.progressView2)
                
            }
            
            
        }
        
        /* This function will display the UIProgressView object. */
        func showProgressView(progressView: UIProgressView){
            
            // Get the progressView's progress.
            var currProgress = progressView.progress
               
            // progress value plus 0.1.
            progressView.progress = currProgress + 0.1
               
            currProgress = progressView.progress
               
            // If current progress value is 1.
            if(currProgress == 1){
                
                // Invalidate the timer object to stop it.
                self.timer?.invalidate()
                   
                // Prompt an alert dialog to show download complete message.
                let alertController:UIAlertController = UIAlertController(title: "Download Progerss", message: "Download complete", preferredStyle: UIAlertController.Style.alert)
                   
                let alertAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler:nil)
                   
                // Add alertAction object to alertController.
                alertController.addAction(alertAction)
                
                // Popup the alert dialog.
                present(alertController, animated: true, completion: nil)
    
                // Set progressView's progress to 0.
                progressView.progress = 0
                
                // Hide the progressView.
                progressView.isHidden = true
    
                // Enable btn1 and btn2.
                self.btn1.isEnabled = true
                self.btn2.isEnabled = true
            }
            
        }
    }
    
    
  5. In the above swift source code, I change the button and progress view’s layout constraints programmatically, you can read How To Change Swift Constraints To Make Autolayout Programmatically to learn more.

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.