Skip to content

Instantly share code, notes, and snippets.

@nil-biribiri
Last active March 11, 2019 05:39
Show Gist options
  • Save nil-biribiri/633e6a0fa50062e665fb293234762013 to your computer and use it in GitHub Desktop.
Save nil-biribiri/633e6a0fa50062e665fb293234762013 to your computer and use it in GitHub Desktop.
Extension for UIActivityIndicatorView in Swift 4.2.
import UIKit
protocol ActivityPresentable {
func presentActivity(_ style: UIActivityIndicatorView.Style,
withTintColor tintColor: UIColor?,
blockSuperView isBlockView: Bool)
func dismissActivity()
}
extension ActivityPresentable where Self: UIViewController {
func presentActivity(_ style: UIActivityIndicatorView.Style = .whiteLarge,
withTintColor tintColor: UIColor? = .appRed1,
blockSuperView isBlockView: Bool = true) {
if let activityIndicator = findActivity() {
activityIndicator.startAnimating()
} else {
let activityIndicator = UIActivityIndicatorView(style: style)
if let tintColor = tintColor {
activityIndicator.assignColor(tintColor)
}
activityIndicator.startAnimating()
view.addSubview(activityIndicator)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor)
])
activityIndicator.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor).isActive = isBlockView
activityIndicator.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor).isActive = isBlockView
} else {
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
activityIndicator.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = isBlockView
activityIndicator.heightAnchor.constraint(equalTo: view.heightAnchor).isActive = isBlockView
}
}
}
func dismissActivity() {
findActivity()?.stopAnimating()
}
func findActivity() -> UIActivityIndicatorView? {
return view.subviews.lazy.compactMap { $0 as? UIActivityIndicatorView }.first
}
}
extension UIActivityIndicatorView {
func assignColor(_ color: UIColor) {
self.color = color
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment