Skip to content

Instantly share code, notes, and snippets.

@NeilsUltimateLab
Last active March 7, 2019 18:04
Show Gist options
  • Save NeilsUltimateLab/f77127f03d5b49f47224e78227bd5f3f to your computer and use it in GitHub Desktop.
Save NeilsUltimateLab/f77127f03d5b49f47224e78227bd5f3f to your computer and use it in GitHub Desktop.
A button with activity indicator in the center.
import UIKit
class IndicatorViewButton: UIButton {
var roundedCornerRequired: Bool = true
private var indicatorView: UIActivityIndicatorView = {
let aiv = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.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.previousText = currentTitle
self.addSubview(indicatorView)
indicatorView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
indicatorView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}
override func layoutSubviews() {
super.layoutSubviews()
if roundedCornerRequired {
self.layer.cornerRadius = self.frame.height / 2
}
self.setTitleColor(.white, for: .normal)
self.setTitle(previousText, for: .normal)
}
override func setTitle(_ title: String?, for state: UIControlState) {
guard !isAnimating else { return }
super.setTitle(title, for: state)
self.previousText = title
}
func startAnimating() {
self.setTitle("", for: .normal)
indicatorView.startAnimating()
}
func stopAnimating() {
self.setTitle(previousText, for: .normal)
self.setTitleColor(.white, for: .normal)
self.indicatorView.stopAnimating()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment