It’s a common task to provide visual cue to the user when a task is in progress. Apple UIKit has the UIActivityIndicatorView UI component for this purpose. The component appears as a “gear” that is either spinning or stopped . In this post, we will extend it:
- Show a transparent overlay over the whole screen or part of the screen. The overlay will prevent user interaction with the covered controls while the task is in progress.
-
Create the animating UIActivityIndicatorView programmatically in the center of the overlay to indicate a task is being processed
-
Show additional text in the overlay to provide additional information
Create the Overlay
We create the overlay as a UIView control.
The frame size of the overlay will be the same as the target it’s covering.
let overlay = UIView(frame: overlayTarget.frame)
Position the overlay to completely cover its target by setting its center to be the same as its target.
overlay.center = overlayTarget.center
Set the overlay alpha to 0 (completely transparent) initially. We will gradually change it to 0.5 later to animate the display of the overlay.
overlay.alpha = 0 overlay.backgroundColor = UIColor.blackColor()
Add the overlay to its target. Bring the overlay to the front to make sure it covers the target and blocks user interaction with other controls on the target.
overlayTarget.addSubview(overlay) overlayTarget.bringSubviewToFront(overlay)
Animate the display of the overlay by gradually changing the alpha value
UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(0.5) overlay.alpha = overlay.alpha > 0 ? 0 : 0.5 UIView.commitAnimations()
Create the UIActivityIndicatorView
let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White) indicator.center = overlay.center indicator.startAnimating() overlay.addSubview(indicator)
Create the Loading Text Label
When loading text is given, we will create a UILabel to show it. We call sizeToFit to resize the label to fit the text. We position the label right below the UIActivityIndicatorView in the overlay.
if let textString = loadingText { let label = UILabel() label.text = textString label.textColor = UIColor.whiteColor() label.sizeToFit() label.center = CGPoint(x: indicator.center.x, y: indicator.center.y + 30) overlay.addSubview(label) }
To Use
Include the LoadingIndicatorView.swift file.
Call one of the show() methods to show the loading indicator before the long running task.
// Show indicator to cover entire screen LoadingIndicatorView.show() // Show indicator to cover entire screen with custom text LoadingIndicatorView.show("Loading") // Show indicator to cover target view LoadingIndicatorView.show(target) // Show indicator to cover target view with custom text LoadingIndicatorView.show(target, "Loading")
Call the hide() method to hide the loading indicator after long running task.
LoadingIndicatorView.hide()