With a UIProgressView, also known as a progress bar, you can show the progress of a task to the user. In this tutorial we use a timer to simulate the progress of a specific task.
Open Xcode and create a new Single View Application. For product name, use ProgressViewDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.
First, Let's create our User Interface. Go to ViewController.xib. 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. The main View should look like this.
In ViewController.m in the interface section declare the following properties.
@interface ViewController ()
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) NSTimer *myTimer;
@property (nonatomic, strong) IBOutlet UILabel *progressLabel;
Go back to ViewController.xib. Select the Assistant Editor. On the right side select ViewController.m. Ctrl-click and drag from the Label to the IBOutlet progressLabel in ViewController.m. Next, Ctrl-click and drag from the start button to the @implementation section in ViewController.m. Create the following IBAction method.
Change the viewDidLoad method to
self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
self.progressView.center = self.view.center;
The progress view is initialized with a default style and centered and added to the main view. Next, let's implement the startCount IBAction method.
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateUI:) userInfo:nil repeats:YES];
We define a timer which will be triggered every second repeatedly. When triggered the updateUI method will be called. Let's create this method.
- (void)updateUI:(NSTimer *)timer
static int count =0; count++;
if (count <=10)
self.progressLabel.text = [NSString stringWithFormat:@"%d %%",count*10];
self.progressView.progress = (float)count/10.0f;
self.myTimer = nil;
The progress property has a value from 0.0 to 1.0. We update the progress with 0.1 at each call. When the count reaches 10(and the progress bar is full) we invalidate the timer. Build and Run, press the start button to see the progress bar fill up.
You can download the source code of the ProgressViewDemo at the ioscreator repository on github.