iOS | Custom Activity Indicator With Image

Manisha Roy
Globant
Published in
2 min readAug 9, 2021

Activity Indicator is the spinning wheel that indicates a task is in progress. Apple have provided the basic UIActivityIndicatorView, but that doesn’t provide appearance customisation with images. In this article we are going to design one custom activity indicator where single image will be animated as spinning wheel. In this article, we are also going to use UIDynamicItemBehaviour and UIDynamicAnimator for giving spinning wheel effect.

Let’s start designing our own awesome and convenient to use custom activity indicator:

Setup Activity Indicator

  1. Declare and initialise UIImageView instance with the image you want to as as spinner.
let theImage = UIImage(named: "activityLoader")
let imageView = UIImageView(image: theImage)
imageView.frame = CGRect(x: self.center.x — 20, y: self.center.y — 20, width: 40, height: 40)

Note: Here self is a UIVIew class instance named as MRActivityIndicator and activityLoader is a image named which will act as spinner.

2. Add dynamic behaviour for dynamic animation on image view.

let spinnerBehavior = UIDynamicItemBehavior(items: [imageView])
let animator = UIDynamicAnimator(referenceView: self)

Show Activity Indicator

  1. Add imageView to the screen and start animation.
func showLoadingActivity() {
addSubview(imageView)
startAnimation()
UIApplication.shared.windows.first?.addSubview(self)
}

Note: If you want to ignore user’s interactions when spinner is shown then please add this in above if-block
UIApplication.shared.beginIgnoringInteractionEvents()

2. In startAnimation(), if animator is not containing spinnerBehavior then add angular velocity with some value(here it’s 5.0) for imageView. Once spinnerBehavior is added to animator, imageView start rotating and will behave like spinning wheel.

func startAnimation() {
if !animator.behaviors.contains(spinnerBehavior) {
spinnerBehavior.addAngularVelocity(5.0, for: imageView)
animator.addBehavior(spinnerBehavior)
}
}

Note: We can increase the velocity for faster spinning effect.

Hide Activity Indicator

To stop the activity indicator, these are the steps we are going to follow:

animator.removeAllBehaviors()
imageView.removeFromSuperview()
imageView = nil
self.removeFromSuperview()

Note: If you have disabled the user’s interaction then please add below code to enable it.
UIApplication.shared.endIgnoringInteractionEvents()

Please find the whole code snippet for Activity Indicator where we have used UIImageView and customised it to act like a spinning wheel.

Usage of MRActivityIndicator

  1. To show it, please use
    MRActivityIndicator.shared.show()
  2. To hide it, please use
    MRActivityIndicator.shared.hide()

If you liked this article then please appreciate it with claps and comments. This will really encourage me to write more!!!!

--

--

Manisha Roy
Globant
Writer for

An enthusiastic iOS Developer. Keep learning!!