|
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 |
|
} |
|
} |