I would like to change the content of a UIButton to an ActivityIndicator after it is pressed.
I know buttons have an imageView and a titleLabel, but I don\'t know how to
Updated selected answer( steve-rosenberg ) for Apple Swift version 3.0.1 (swiftlang-800.0.58.6 clang-800.0.42.1) Xcode 8.1 (8B62)
import ObjectiveC
private var originalButtonText: String?
private var activityIndicator: UIActivityIndicatorView!
extension UIButton{
func showLoading() {
originalButtonText = self.titleLabel?.text
self.setTitle("", for: .normal)
if (activityIndicator == nil) {
activityIndicator = createActivityIndicator()
}
showSpinning()
}
func hideLoading() {
self.setTitle(originalButtonText, for: .normal)
activityIndicator.stopAnimating()
}
private func createActivityIndicator() -> UIActivityIndicatorView {
let activityIndicator = UIActivityIndicatorView()
activityIndicator.hidesWhenStopped = true
activityIndicator.color = UIColor.lightGray
return activityIndicator
}
func showSpinning() {
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(activityIndicator)
centerActivityIndicatorInButton()
activityIndicator.startAnimating()
}
private func centerActivityIndicatorInButton() {
let xCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: activityIndicator, attribute: .centerX, multiplier: 1, constant: 0)
self.addConstraint(xCenterConstraint)
let yCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: activityIndicator, attribute: .centerY, multiplier: 1, constant: 0)
self.addConstraint(yCenterConstraint)
}
}