68

Progress View iOS Tutorial

 5 years ago
source link: https://www.tuicool.com/articles/hit/A3uANv3
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

With a progress view the progress of a task can be displayed. In this tutorial we will simulate the progress of a specific task. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

ayqU3iZ.png!web

For product name, use IOSProgressViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

QRfErme.png!web

Go to the Storyboard . Drag a button and a label to the main view. Give the button a name of "Start" and the label a name of "0 %". We will dynamically update this label later. Also drag a Progress View to the main view. The main View should look like this.

VZVFrea.png!web

Select the Assistant Editor. Ctrl-click and drag from the Label to the ViewController class in the ViewController.swift file and create the following outlet

vIVJF3y.png!web

Ctrl-click and drag from the Progress View to the ViewController class in the ViewController.swift file and create the following outlet

INVRBju.png!web

Next, Ctrl-click and drag from the start button to the ViewController class and create the following action

3aEr6jM.png!web

Go to ViewController .swift and add the following property

let progress = Progress(totalUnitCount: 10)

The Progress object is used to keep track of the progress. This will be divided into 10 units, since we will update the bar with 10% until it reaches 100%. Next, implement the startCount(_:) method

@IBAction func startCount(sender: UIButton) {
    // 1
    progressView.progress = 0.0
    progress.completedUnitCount = 0

    // 2
    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
        guard self.progress.isFinished == false else {
            timer.invalidate()
            return
        }
        
        // 3
        self.progress.completedUnitCount += 1
        self.progressView.setProgress(Float(self.progress.fractionCompleted), animated: true)

        self.progressLabel.text = "\(Int(self.progress.fractionCompleted * 100)) %"
    }
}
  1. When the start button is clicked. the progress bar is reset to 0

  2. Every second the progress bar will be updated, when finished the method returns

  3. The progress bar will be incremented with 1 and the label will be incremented by 10%

Build and Runthe project, press the Start button and the progress view will animate till it reaches 100%.

ruaAvmz.png!web

You can download the source code of the iOSProgressViewTutorial at the ioscreator repository on  github .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK