How do I place my activityIndicator programmatically?

Swift 5:

let activityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray)

    // Place the activity indicator on the center of your current screen
            myActivityIndicator.center = view.center

    // In most cases this will be set to true, so the indicator hides when it stops spinning
            myActivityIndicator.hidesWhenStopped = true

    // Start the activity indicator and place it onto your view
            myActivityIndicator.startAnimating()
            view.addSubview(myActivityIndicator)

    // Do something here, for example fetch the data from API


    // Finally after the job above is done, stop the activity indicator
            myActivityIndicator.stopAnimating()

Swift 4, Swift 5

Here if you prefer my daily/favorite programmatic pattern

// MARK: - Component
lazy var indicatorView: UIActivityIndicatorView = {
  let view = UIActivityIndicatorView(style: .medium)
  view.color = .white
  view.startAnimating()
  view.translatesAutoresizingMaskIntoConstraints = false
  return view
}()

// MARK: - Life Cycle
override func viewDidLoad() {
  super.viewDidLoad()
  setupViews()
  setupLayouts()
}

func setupViews() {
  addSubview(indicatorView)
}

    
func setupLayouts() {
  NSLayoutConstraint.activate([
    indicatorView.centerXAnchor.constraint(equalTo: centerXAnchor),
    indicatorView.centerYAnchor.constraint(equalTo: centerYAnchor)
  ])
}

You can declare:

var activityView: UIActivityIndicatorView?

And, in your class, create the next methods for showing or hiding the indicator:

func showActivityIndicator() {
    activityView = UIActivityIndicatorView(style: .large)
    activityView?.center = self.view.center
    self.view.addSubview(activityView!)
    activityView?.startAnimating()
}

func hideActivityIndicator(){
    if (activityView != nil){
        activityView?.stopAnimating()
    }
}

This code works for me. Good luck!


Basically, you can do this in just a few lines of code:

 func showActivityIndicatory() {
    let activityView = UIActivityIndicatorView(style: .whiteLarge)
    activityView.center = self.view.center
    self.view.addSubview(activityView)
    activityView.startAnimating()
}

If you need more controll on activityView please set Origin of container view to place activityindicator anywhere on the screen.

func showActivityIndicatory() {
    let container: UIView = UIView()
    container.frame = CGRect(x: 0, y: 0, width: 80, height: 80) // Set X and Y whatever you want
    container.backgroundColor = .clear
    
    let activityView = UIActivityIndicatorView(style: .whiteLarge)
    activityView.center = self.view.center
    
    container.addSubview(activityView)
    self.view.addSubview(container)
    activityView.startAnimating()
}