Last active
October 28, 2019 09:14
-
-
Save ahbou/916c26c7d06e58fa608dda0a4a30f9a0 to your computer and use it in GitHub Desktop.
Dead Simple HUD implementation in swift with a title and an Acitivity indicator
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
import UIKit | |
class HUD: UIView { | |
private lazy var backView: UIView = UIView(frame: bounds) | |
private let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView(style: .whiteLarge) | |
private lazy var titleLabel: UILabel = { | |
let title = UILabel() | |
title.font = UIFont.boldSystemFont(ofSize: 16) | |
title.textColor = headerColor | |
title.textAlignment = .center | |
return title | |
}() | |
private var headerColor = UIColor.white | |
private var backColor = UIColor.black | |
private var loaderColor = UIColor.white | |
// MARK: Public Methods | |
public static func showInView(_ view: UIView, title: String? = nil) { | |
hideInView(view) // prevents adding more than one | |
guard let window = view.window else { | |
return | |
} | |
DispatchQueue.main.async { | |
let hud = HUD() | |
hud.frame = UIScreen.main.bounds | |
hud.setupOverlay() | |
hud.setupActivityIndicator() | |
if let title = title { | |
hud.setupTitle(text: title) | |
} | |
window.addSubview(hud) | |
} | |
} | |
// Removes all HUDs from the window | |
public static func hideInView(_ view: UIView) { | |
guard let window = view.window else { | |
return | |
} | |
DispatchQueue.main.async { | |
window.subviews | |
.filter({ $0 is HUD }) | |
.forEach({ $0.removeFromSuperview() }) | |
} | |
} | |
// MARK: - Set view properties | |
private func setupOverlay() { | |
if let old = backView.viewWithTag(1001) as UIView? { | |
old.removeFromSuperview() | |
} | |
let translucentView = UIView(frame: backView.bounds) | |
translucentView.backgroundColor = backColor | |
translucentView.alpha = 0.75 | |
translucentView.tag = 1001 | |
backView.addSubview(translucentView) | |
addSubview(backView) | |
} | |
private func setupActivityIndicator() { | |
activityIndicator.style = .whiteLarge | |
activityIndicator.color = loaderColor | |
activityIndicator.backgroundColor = UIColor.clear | |
activityIndicator.startAnimating() | |
activityIndicator.center = center | |
addSubview(activityIndicator) | |
} | |
private func setupTitle(text: String) { | |
titleLabel.text = text | |
titleLabel.sizeToFit() | |
titleLabel.adjustsFontSizeToFitWidth = true | |
let xPos = bounds.midX - titleLabel.bounds.midX | |
let yPos = activityIndicator.frame.maxY + 5 | |
titleLabel.frame.origin = CGPoint(x: xPos, y: yPos) | |
addSubview(titleLabel) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment