Last active
March 11, 2019 05:39
-
-
Save nil-biribiri/633e6a0fa50062e665fb293234762013 to your computer and use it in GitHub Desktop.
Extension for UIActivityIndicatorView in Swift 4.2.
This file contains 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 | |
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