Created
January 24, 2020 05:34
-
-
Save achernoprudov/a8fe89ef1e2060c8b23a2394b70c703f to your computer and use it in GitHub Desktop.
Simple abstraction for hud controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Controller for `HUD` visibility management. | |
/// Shows hud with delay to prevent interface blinking. | |
public class HudController { | |
// MARK: - Instance variables | |
private let container: UIView | |
private let delay: DispatchTimeInterval | |
private var hud: UIActivityIndicatorView? | |
private var showHudWork: DispatchWorkItem? | |
// MARK: - Public | |
public init( | |
container: UIView, | |
delay: DispatchTimeInterval = .milliseconds(300) | |
) { | |
self.container = container | |
self.delay = delay | |
} | |
public func setHud(visible: Bool) { | |
visible ? showIfNeeded() : hideIfNeeded() | |
} | |
// MARK: - Private | |
private func showIfNeeded() { | |
if hud != nil || showHudWork != nil { | |
return | |
} | |
let showHudWork = DispatchWorkItem { [weak self] in | |
self?.addHudToContainer() | |
} | |
self.showHudWork = showHudWork | |
DispatchQueue.main.asyncAfter( | |
deadline: .now() + delay, | |
execute: showHudWork | |
) | |
} | |
private func hideIfNeeded() { | |
showHudWork?.cancel() | |
showHudWork = nil | |
hud?.stopAnimating() | |
hud?.removeFromSuperview() | |
hud = nil | |
} | |
private func addHudToContainer() { | |
let hud = UIActivityIndicatorView(style: .large) | |
self.hud = hud | |
container.addSubview(hud) | |
hud.startAnimating() | |
showHudWork = nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment