[iphone] How to display activity indicator in middle of the iphone screen?

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

This question is related to iphone ios ipad

The answer is


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

    activityView.center=self.view.center;
    [activityView startAnimating];
    [self.view addSubview:activityView];

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.


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)
    }
}

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)

    }
}

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]];

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!!!


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
}

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();

}

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];

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/


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()
        }
    }
    

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];

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)

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),
    ])
}

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.....


Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to ipad

What is correct media query for IPad Pro? iPad Multitasking support requires these orientations How to restrict UITextField to take only numbers in Swift? How to present a modal atop the current view in Swift Presenting a UIAlertController properly on an iPad using iOS 8 Detect current device with UI_USER_INTERFACE_IDIOM() in Swift HTML5 Video tag not working in Safari , iPhone and iPad Install .ipa to iPad with or without iTunes How to hide UINavigationBar 1px bottom line How to fix UITableView separator on iOS 7?