Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I place my activityIndicator programmatically?

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.

like image 920
user9123 Avatar asked Mar 06 '18 12:03

user9123


2 Answers

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()
}
like image 50
Usman Javed Avatar answered Oct 04 '22 03:10

Usman Javed


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!

like image 23
jframosg Avatar answered Oct 04 '22 03:10

jframosg