Here is a solution that will create a simple loader view on top of the presented view,
First, we need to create a class that is responsible for adding/removing an activityIndicator
class AppLoaderView : UIView{
fileprivate
lazy var circularProgressIndicator : UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
activityIndicator.center = self.center
activityIndicator.style = .gray
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.hidesWhenStopped = true
self.addSubview(activityIndicator)
return activityIndicator
}()
func showSpinning() {
setupConstraints()
circularProgressIndicator.startAnimating()
}
private
func setupConstraints() {
let xCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerX,
relatedBy: .equal, toItem: circularProgressIndicator,
attribute: .centerX,
multiplier: 1,
constant: 0)
self.addConstraint(xCenterConstraint)
let yCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerY,
relatedBy: .equal, toItem: circularProgressIndicator,
attribute: .centerY,
multiplier: 1,
constant: 0)
self.addConstraint(yCenterConstraint)
}
func removeLoading() {
circularProgressIndicator.stopAnimating()
}
}
Now we will create an extension on viewController, that has two methods one for showing the LoaderView and one for removing it,
extension UIViewController{
private var loaderView : AppLoaderView?{
if let view = self.view.subviews.first(where: { $0 is AppLoaderView}) as? AppLoaderView { return view }
let view = AppLoaderView(frame: self.view.frame)
view.backgroundColor = .white
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
view.isHidden = true
return view
}
func showLoaderView(){
if let view = loaderView {
self.view.addSubview(view)
self.view.bringSubviewToFront(view)
view.isHidden = false
view.clipsToBounds = true
view.layoutIfNeeded()
view.showSpinning()
}
}
func removeLoaderView(){
if let view = loaderView{
view.removeLoading()
view.removeFromSuperview()
self.view.layoutIfNeeded()
}
}
}
That's it, now with your example you can call self.showLoaderView() when the button clicked, and once the API call returns you will call self.removeLoaderView().
Add these somewhere in your project, and on any viewController you can call these methods to show/hide your loaderView.