How to create a loading view in UIView using extension
import UIKit
import ObjectiveC
extension UIView {
private struct AssociatedKeys {
static var LoadingDescriptiveName = "loading_nsh_DescriptiveName"
static var LoadingViewDescriptiveName = "loading_view_nsh_DescriptiveName"
}
private func updateLoadingView(shouldShow: Bool) {
if shouldShow {
loadingView.startAnimating()
addSubview(loadingView)
loadingView.isHidden = false
if let superview = loadingView.superview {
loadingView.backgroundColor = superview.backgroundColor
loadingView.centerXAnchor.constraint(equalTo: superview.centerXAnchor).isActive = true
loadingView.centerYAnchor.constraint(equalTo: superview.centerYAnchor).isActive = true
}
} else {
UIView.transition(with: self,
duration: 0.35,
options: .transitionCrossDissolve,
animations: { [weak self] in
self?.loadingView.removeFromSuperview()
}, completion: nil)
}
}
@objc var loading: Bool {
get {
guard let isLoading = objc_getAssociatedObject(self, &AssociatedKeys.LoadingDescriptiveName) as? Bool else { return false }
return isLoading
}
set {
objc_setAssociatedObject(self,
&AssociatedKeys.LoadingDescriptiveName,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
updateLoadingView(shouldShow: newValue)
}
}
private var loadingView: UIActivityIndicatorView {
if let view = objc_getAssociatedObject(self, &AssociatedKeys.LoadingViewDescriptiveName) as? UIActivityIndicatorView {
return view
} else {
let loadingView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
loadingView.hidesWhenStopped = true
loadingView.clipsToBounds = true
loadingView.stopAnimating()
loadingView.translatesAutoresizingMaskIntoConstraints = false
objc_setAssociatedObject(self,
&AssociatedKeys.LoadingViewDescriptiveName,
loadingView,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return loadingView
}
}
}
source:
d