Files
suixinkan_uikit/suixinkan/UI/Loading/GlobalLoadingManager.swift

75 lines
2.0 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// GlobalLoadingManager.swift
// suixinkan
//
import UIKit
/// Loading Android `GlobalLoadingManager`
@MainActor
final class GlobalLoadingManager {
static let shared = GlobalLoadingManager()
private var loadingCount = 0
private weak var hostWindow: UIWindow?
private var overlayView: GlobalLoadingOverlayView?
private init() {}
/// Loading
var isShowing: Bool {
loadingCount > 0
}
/// Loading
func show() {
loadingCount += 1
guard loadingCount == 1 else { return }
attachOverlayIfNeeded()
overlayView?.present()
}
/// Loading
func hide() {
guard loadingCount > 0 else { return }
loadingCount -= 1
guard loadingCount == 0 else { return }
overlayView?.dismiss()
overlayView?.removeFromSuperview()
}
/// Loading
func hideAll() {
loadingCount = 0
overlayView?.dismiss()
overlayView?.removeFromSuperview()
}
private func attachOverlayIfNeeded() {
guard let window = keyWindow else { return }
hostWindow = window
if overlayView == nil {
let overlay = GlobalLoadingOverlayView(frame: window.bounds)
overlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
overlay.isHidden = true
overlayView = overlay
}
guard let overlayView else { return }
if overlayView.superview !== window {
overlayView.removeFromSuperview()
window.addSubview(overlayView)
}
window.bringSubviewToFront(overlayView)
}
private var keyWindow: UIWindow? {
UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap(\.windows)
.first { $0.isKeyWindow }
}
}