Search code examples
iosswiftuiviewuiprogressview

How to create view programmatically outside a view controller


Currently I'm trying to create a UIProgressView that will be called with a manager class:

 func addProgressBar() {

        let rect = CGRect(x: 10, y: 70, width: 250, height: 0)
        let progressView = UIProgressView(frame: rect)
        progressView.progress = 0.0
        progressView.tintColor = UIColor.blue
        self.view.addSubview(progressView)
    }

This issue that's arising is the line:

 self.view.addSubview(progressView)

because the function isn't in a viewController I get the error:

Value of type 'NetworkHelper' has no member 'view'

any idea how to add the progressView outside of a viewcontroller?


Solution

  • Well, you probably guessed it yourself, you need a view to which you would put the progressBar. I think the caller of the addProgressBar method should know the best where it would fit the best, so I would recommend using progressBar with an argument of a UIViewController type, which would be the target which is responsible for making a network call and thus is a target to put the progress bar into:

    func addProgressBar(targetViewController: UIViewController) {
        // moreover, are you sure here that the height of the progressBar should be 0?
        let rect = CGRect(x: 10, y: 70, width: 250, height: 0)
        let progressView = UIProgressView(frame: rect)
        progressView.progress = 0.0
        progressView.tintColor = UIColor.blue
        targetViewController.view.addSubview(progressView)
    }