Skip to content

Instantly share code, notes, and snippets.

@rajohns08
Created November 13, 2015 04:55
Show Gist options
  • Save rajohns08/9463be5b2921cbec828d to your computer and use it in GitHub Desktop.
Save rajohns08/9463be5b2921cbec828d to your computer and use it in GitHub Desktop.
iOS / Swift - UIButton subclass for showing loading spinner aka activity indicator inside button
import UIKit
class LoadingButton: UIButton {
var originalButtonText: String?
var activityIndicator: UIActivityIndicatorView!
func showLoading() {
originalButtonText = self.titleLabel?.text
self.setTitle("", forState: UIControlState.Normal)
if (activityIndicator == nil) {
activityIndicator = createActivityIndicator()
}
showSpinning()
}
func hideLoading() {
self.setTitle(originalButtonText, forState: UIControlState.Normal)
activityIndicator.stopAnimating()
}
private func createActivityIndicator() -> UIActivityIndicatorView {
let activityIndicator = UIActivityIndicatorView()
activityIndicator.hidesWhenStopped = true
activityIndicator.color = UIColor.lightGrayColor()
return activityIndicator
}
private 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)
}
}
@ty-kim
Copy link

ty-kim commented Nov 16, 2023

Thank you so much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment