NewDev
NewDev

Reputation: 9

Cannot find 'view' in scope swift 5

I understand that this is newbie question but I can not find answer on stackoverflow or google.

I created swift file with a function which access/call in every controller.

func showActivityIndicator(show: Bool) {      
    var activityIndicator : NVActivityIndicatorView!
    let xAxis = view.center.x // or use (view.frame.size.width / 2) //error 
    let yAxis = view.center.y // or use (view.frame.size.height / 2)//error
    let size = CGRect(x: (xAxis - 50), y: (yAxis - 50), width: 45, height: 45)
    activityIndicator = NVActivityIndicatorView(frame: size)
    activityIndicator.type = .ballSpinFadeLoader // add your type
    activityIndicator.color = UIColor.red // add your color
    if show {
        activityIndicator.startAnimating()
    } else {
        activityIndicator.stopAnimating()
    }
}

but it gives me Cannot find 'view' in scope error.Thank you in advance!

Upvotes: 0

Views: 3636

Answers (2)

Teddichiiwa
Teddichiiwa

Reputation: 791

You could create an extension. You can do that like this:

extension UIViewController {
   func showActivityIndicator(show: Bool) {
          
           var activityIndicator : NVActivityIndicatorView!
           let xAxis = view.center.x // or use (view.frame.size.width / 2) //error 
           let yAxis = view.center.y // or use (view.frame.size.height / 2)//error
           let size = CGRect(x: (xAxis - 50), y: (yAxis - 50), width: 45, height: 45)
           activityIndicator = NVActivityIndicatorView(frame: size)
           activityIndicator.type = .ballSpinFadeLoader // add your type
           activityIndicator.color = UIColor.red // add your color

           if show {
               activityIndicator.startAnimating()
           } else {
               activityIndicator.stopAnimating()
           }
       }
}

Upvotes: 2

Marcin Żmigrodzki
Marcin Żmigrodzki

Reputation: 393

It works if you place your function in a class derived from UIViewController or as suggested you add extension to the class. I tested your function on my application and there were no problems with "view.center.x".

Upvotes: 0

Related Questions