How do I place my activityIndicator programmatically?

user9123 picture user9123 · Mar 6, 2018 · Viewed 15.2k times · Source

I want to place my activityIndicator where I want it programmatically, but I don´t know how.

I know how to put it in the center of the screen:

activityIndicator.center = self.view.center

But I want something like this:

activityIndicator.activityIndicator(frame: CGRect(x: 100, y: 100, width: 100, height: 50))

But I can´t seem to make it work.

Answer

Usman Javed picture Usman Javed · Mar 6, 2018

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

 func showActivityIndicatory() {
    var 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()
}