80

When we draw the image, we want to display the activity indicator. Can anyone help us?

1

15 Answers 15

150
UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc]     
        initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    activityView.center=self.view.center;
    [activityView startAnimating];
    [self.view addSubview:activityView];
3
  • 14
    i would add also activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin; for proper landscape orientation look and rotation
    – adsurbum
    Jan 21, 2014 at 20:30
  • 1
    @adsurbum Thank you! It was the key to make it centered on all size of iPhone screens from SE to 8 Plus! In Swift, it's: activityView.autoresizingMask = [ .flexibleLeftMargin, .flexibleTopMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleWidth, .flexibleHeight ]
    – balazs630
    Jun 13, 2019 at 16:08
  • +1 to adsurbum's comment. Setting the center stopped working in my app recently. Setting the autoresizingMask fixed it. Before doing that it would just always appear in the upper left corner no matter what I set the .center to.
    – Baxissimo
    Feb 17, 2021 at 16:28
46

If you are using Swift, this is how you do it

let activityView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityView.center = self.view.center
activityView.startAnimating()

self.view.addSubview(activityView)
0
16

Code updated for Swift 3

enter image description here

Swift code

import UIKit
class ViewController: UIViewController {

    let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)

    @IBOutlet weak var myBlueSubview: UIView!

    @IBAction func showButtonTapped(sender: UIButton) {
        activityIndicator.startAnimating()
    }

    @IBAction func hideButtonTapped(sender: UIButton) {
        activityIndicator.stopAnimating()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // set up activity indicator
        activityIndicator.center = CGPoint(x: myBlueSubview.bounds.size.width/2, y: myBlueSubview.bounds.size.height/2)
        activityIndicator.color = UIColor.yellow
        myBlueSubview.addSubview(activityIndicator)
    }
}

Notes

  • You can center the activity indicator in middle of the screen by adding it as a subview to the root view rather than myBlueSubview.

    activityIndicator.center =  CGPoint(x: self.view.bounds.size.width/2, y: self.view.bounds.size.height/2)
    self.view.addSubview(activityIndicator)
    
  • You can also create the UIActivityIndicatorView in the Interface Builder. Just drag an Activity Indicator View onto the storyboard and set the properties. Be sure to check Hides When Stopped. Use an outlet to call startAnimating() and stopAnimating(). See this tutorial.

enter image description here

  • Remember that the default color of the LargeWhite style is white. So if you have a white background you can't see it, just change the color to black or whatever other color you want.

    activityIndicator.color = UIColor.black
    
  • A common use case would be while a background task runs. Here is an example:

    // start animating before the background task starts
    activityIndicator.startAnimating()
    
    // background task
    DispatchQueue.global(qos: .userInitiated).async {
    
        doSomethingThatTakesALongTime()
    
        // return to the main thread
        DispatchQueue.main.async {
    
            // stop animating now that background task is finished
            self.activityIndicator.stopAnimating()
        }
    }
    
13

This is the correct way:

UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.center = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0);
[self.view addSubview: activityIndicator];

[activityIndicator startAnimating];

[activityIndicator release];

Setup your autoresizing mask if you support rotation. Cheers!!!

5

Swift 4, Autolayout version

func showActivityIndicator(on parentView: UIView) {
    let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    activityIndicator.startAnimating()
    activityIndicator.translatesAutoresizingMaskIntoConstraints = false

    parentView.addSubview(activityIndicator)

    NSLayoutConstraint.activate([
        activityIndicator.centerXAnchor.constraint(equalTo: parentView.centerXAnchor),
        activityIndicator.centerYAnchor.constraint(equalTo: parentView.centerYAnchor),
    ])
}
2
  • 1
    Welcome to S/O, your answer should never be 100% code.. Always add some explanation. Aug 19, 2018 at 10:40
  • Not sure if this is a black and white rule. If the scope of the question is simple enough and the code self-explanatory, I think it's totally fine to have an code-only answer. @Orkhan's answer is spot on. Feb 5, 2020 at 20:49
4

Try this way

UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.frame = CGRectMake(10.0, 0.0, 40.0, 40.0);
    activityIndicator.center = super_view.center;
    [super_view addSubview: activityIndicator];

[activityIndicator startAnimating];
4

If you want to add a text along with activity indicator please look at http://nullpointr.wordpress.com/2012/02/27/ios-dev-custom-activityindicatorview/

1
  • Your shared link is appreciated but you should make us understand the steps so that everyone gets the clean way to get it.
    – Raj Aryan
    Jan 24, 2018 at 8:53
2

You can set the position like this

        UIActivityIndicatorView *activityView = 
[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityView.frame = CGRectMake(120, 230, 50, 50);
[self.view addSubview:activityView];

Accordingly change the frame size.....

2

If you want to center the spinner using AutoLayout, do:

UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[activityView startAnimating];
[self.view addSubview:activityView];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:activityView
                                                      attribute:NSLayoutAttributeCenterX
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeCenterX
                                                     multiplier:1.0
                                                       constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:activityView
                                                      attribute:NSLayoutAttributeCenterY
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeCenterY
                                                     multiplier:1.0
                                                       constant:0.0]];
2

Swift 3, xcode 8.1

You can use small extension to place UIActivityIndicatorView in the centre of UIView and inherited UIView classes:

Code

extension UIActivityIndicatorView {

    convenience init(activityIndicatorStyle: UIActivityIndicatorViewStyle, color: UIColor, placeInTheCenterOf parentView: UIView) {
        self.init(activityIndicatorStyle: activityIndicatorStyle)
        center = parentView.center
        self.color = color
        parentView.addSubview(self)
    }
}

How to use

let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge, color: .gray,  placeInTheCenterOf: view)
activityIndicator.startAnimating()

Full Example

In this example UIActivityIndicatorView placed in the centre of the ViewControllers view:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge, color: .gray,  placeInTheCenterOf: view)
        activityIndicator.startAnimating()
    }
}

extension UIActivityIndicatorView {

    convenience init(activityIndicatorStyle: UIActivityIndicatorViewStyle, color: UIColor, placeInTheCenterOf parentView: UIView) {
        self.init(activityIndicatorStyle: activityIndicatorStyle)
        center = parentView.center
        self.color = color
        parentView.addSubview(self)
    }
}
1

For Swift 3 you can use the following:

 func setupSpinner(){
    spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height:40))
    spinner.color = UIColor(Colors.Accent)
    self.spinner.center = CGPoint(x:UIScreen.main.bounds.size.width / 2, y:UIScreen.main.bounds.size.height / 2)
    self.view.addSubview(spinner)
    spinner.hidesWhenStopped = true
}
0

Hope this will work:

// create activity indicator 
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] 
    initWithFrame:CGRectMake(0.0f, 0.0f, 20.0f, 20.0f)];
[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];

...
 [self.view addSubview:activityIndicator];
// release it
[activityIndicator release];
0

If you want to try to do it by using interface, you can view my video for this. This way, you no need to write any code to show Activity Indicator in the middle of the iPhone screen.

0
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textLbl: UILabel!

    var containerView = UIView()
    var loadingView = UIView()
    var activityIndicator = UIActivityIndicatorView()

    override func viewDidLoad() {
        super.viewDidLoad()

        let _  = Timer.scheduledTimer(withTimeInterval: 10, repeats: false) { (_) in
            self.textLbl.text = "Stop ActivitiIndicator"
            self.activityIndicator.stopAnimating()
            self.containerView.removeFromSuperview()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func palyClicked(sender: AnyObject){

        containerView.frame = self.view.frame
        containerView.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.3)
        self.view.addSubview(containerView)

        loadingView.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
        loadingView.center = self.view.center
        loadingView.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.5)
        loadingView.clipsToBounds = true
        loadingView.layer.cornerRadius = 10
        containerView.addSubview(loadingView)

        activityIndicator.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge
        activityIndicator.center = CGPoint(x:loadingView.frame.size.width / 2, y:loadingView.frame.size.height / 2);
        activityIndicator.startAnimating()
        loadingView.addSubview(activityIndicator)

    }
}
1
  • Thanks Thongchai! Can you add some additional text explaining your code? Dec 21, 2016 at 0:06
-1

I found a way to display activity Indicator with minimum code:

first of all import your UI Kit

import UIKit;

Then you have to initiate activity indicator

let activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView();

Then just copy paste this functions below which are self explainatory and call them whereever you need them:

func startLoading(){
    activityIndicator.center = self.view.center;
    activityIndicator.hidesWhenStopped = true;
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray;
    view.addSubview(activityIndicator);

    activityIndicator.startAnimating();
    UIApplication.shared.beginIgnoringInteractionEvents();

}

func stopLoading(){ 

    activityIndicator.stopAnimating();
    UIApplication.shared.endIgnoringInteractionEvents();

}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.