Skip to content

Instantly share code, notes, and snippets.

@NeilsUltimateLab
Created June 17, 2019 16:05
Show Gist options
  • Save NeilsUltimateLab/3c3da159bd2746efe8ff1ef6c2ff0839 to your computer and use it in GitHub Desktop.
Save NeilsUltimateLab/3c3da159bd2746efe8ff1ef6c2ff0839 to your computer and use it in GitHub Desktop.
import UIKit
class IndicatorButton: UIButton {
private var indicatorView: UIActivityIndicatorView = {
let aiv = UIActivityIndicatorView(style: .white)
aiv.hidesWhenStopped = true
aiv.translatesAutoresizingMaskIntoConstraints = false
aiv.isUserInteractionEnabled = false
return aiv
}()
var isAnimating: Bool {
return indicatorView.isAnimating
}
private var previousText: String?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
self.layer.shadowColor = UIColor.clear.cgColor
self.previousText = currentTitle
self.addSubview(indicatorView)
indicatorView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
indicatorView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
indicatorView.color = self.tintColor
}
override func setTitle(_ title: String?, for state: UIControl.State) {
guard !isAnimating else { return }
super.setTitle(title, for: state)
if title?.isEmpty ?? true {
return
}
self.previousText = title
}
func startAnimating() {
self.setTitle("", for: .normal)
indicatorView.startAnimating()
self.isEnabled = false
}
func stopAnimating() {
self.isEnabled = true
self.indicatorView.stopAnimating()
self.setTitle(previousText, for: .normal)
}
}
extension String {
var validOptionalString: String? {
if self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return nil
}
return self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment