Skip to content

Instantly share code, notes, and snippets.

@strzempa
Created November 23, 2019 10:23
Show Gist options
  • Save strzempa/fcd0350e6e96a287e587b3a2b9e598e6 to your computer and use it in GitHub Desktop.
Save strzempa/fcd0350e6e96a287e587b3a2b9e598e6 to your computer and use it in GitHub Desktop.
while text is nil or empty display activity indicator on uilabel
import UIKit
class LabelWithActivityIndicator: UILabel {
private var activityIndicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(style: .gray)
indicator.startAnimating()
indicator.hidesWhenStopped = true
return indicator
}()
override var text: String? {
didSet {
guard let text = text,
!text.isEmpty else {
showLoading()
return
}
hideLoading()
}
}
}
private extension LabelWithActivityIndicator {
private func showLoading() {
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
addSubview(activityIndicator)
activityIndicator.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
activityIndicator.topAnchor.constraint(equalTo: topAnchor).isActive = true
activityIndicator.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
activityIndicator.startAnimating()
}
private func hideLoading() {
activityIndicator.stopAnimating()
activityIndicator.removeFromSuperview()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment