How To Use iOS Progress View Programmatically In Swift

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

1. Swift Progress View Example Video Demo.

There are two button and two progress view in this example. The top button and the progress view is added in Main.storyboard visually. The bottom button and progress view is added in swift source code programmatically.

When the app start, the progress view are all hidden. When you press one button, the related progress view will be displayed and animated, all the button will be disable. When the progress view animate complete, it will be hidden again, and the buttons will be enabled.

2. Swift Progress View Example Source Code.

  1. Create a Xcode project with 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 ).
    ios swift progress view object in ui library
  3. Add below layout constraints 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 below source code into it. You can see the code in function initProgressView2Btn2 to learn how to create and use 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 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.
READ :   How To Change Swift Constraints To Make Autolayout Programmatically

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.