Protocol reusable Spinner one liner progressview

41 Views Asked by At

This is my code at the moment I instead of using progressView as

self.progressView = showProgressView()

I want to use it as self.showProgress() as a one liner

this is my current protocol


protocol Loadable {
    var progressView: ProgressView? { get }
    func showProgressView() -> ProgressView
    func hideProgressView()
}

extension Loadable where Self: UIViewController {
    func showProgressView() -> ProgressView {
        let pv = ProgressView(frame: CGRect.zero)
        view.addSubview(pv)
        pv.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate(pv.setConstraints(boundsOf: view))
        UIView.animate(withDuration: 0.3) {
            pv.alpha = 1.0
        }
        return pv
    }

    func hideProgressView() {
        guard let progressView = progressView else { return }

        UIView.animate(withDuration: 0.6) {
            progressView.alpha = 0.0
        } completion: { finished in
            progressView.removeFromSuperview()
        }
    }
}```


//this is my current usage on the code


@objc private func loadData() {
        print("Calling API")
        
        self.progressView = showProgressView()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0){
            self.civilizationData()
            self.hideProgressView()
        }
    }

//tried using this method

protocol Loadable {
    var progressView: ProgressView? { get }
    func showProgressView()
    func hideProgressView()
}

extension Loadable where Self: UIViewController {
    func showProgressView()  {
        let progressView = ProgressView(frame: CGRect.zero)
        view.addSubview(progressView)
        progressView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate(progressView.setConstraints(boundsOf: view))
        UIView.animate(withDuration: 0.3) {
            progressView.alpha = 1.0
        }
        
    }

//but the added subview of my progressview doesn't disappear
protocol Loadable {
    var progressView: ProgressView? { get }
    func showProgressView()
    func hideProgressView()
}

extension Loadable where Self: UIViewController {
    func showProgressView()  {
        let progressView = ProgressView(frame: CGRect.zero)
        view.addSubview(progressView)
        progressView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate(progressView.setConstraints(boundsOf: view))
        UIView.animate(withDuration: 0.3) {
            progressView.alpha = 1.0
        }
        
    }
0

There are 0 best solutions below