UIActivityIndicatorViewを簡単に表示したい

こういうぐるぐるを表示したくて調べたら、こちら↓の記事を見つけました。
LoadingView表示用のUIViewのExtensionを作る
ありがとうございます!
UIViewControllerのextensionにしてみた
記事を参考にして、 UIActivityIndicatorView を UIViewController の extension にしてみました。
extension UIViewController {
func showLoading(style indicatorStyle: UIActivityIndicatorView.Style) {
let overLayView = LoadingOverlayView(frame: view.frame, indicatorStyle: indicatorStyle)
view.addSubview(overLayView)
DispatchQueue.main.async {
overLayView.startAnimation()
}
}
func hideLoading() {
view.subviews.forEach { subView in
if let subView = subView as? LoadingOverlayView {
DispatchQueue.main.async {
subView.stopAnimation()
subView.removeFromSuperview()
}
}
}
}
}
fileprivate final class LoadingOverlayView: UIView {
private var indicatorView: UIActivityIndicatorView!
init(frame: CGRect, indicatorStyle: UIActivityIndicatorView.Style) {
super.init(frame: frame)
indicatorView = UIActivityIndicatorView(style: indicatorStyle)
indicatorView.hidesWhenStopped = true
addSubview(indicatorView)
indicatorView.center = center
backgroundColor = UIColor.black
alpha = 0.5
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func startAnimation() {
indicatorView.startAnimating()
}
func stopAnimation() {
indicatorView.stopAnimating()
}
}
UIActivityIndicatorViewを表示するには
UIActivityIndicatorViewを表示するには、 ViewController の好きなところで showLoading 呼び出すだけです。
止めるときには、 hideLoading を呼び出してください。
func showActivityIndicator() {
showLoading(style: .whiteLarge)
}
func hideActivityIndicator() {
hideLoading()
}