Skip to content

Instantly share code, notes, and snippets.

@rajohns08
Created November 13, 2015 04:55
Show Gist options
  • Select an option

  • Save rajohns08/9463be5b2921cbec828d to your computer and use it in GitHub Desktop.

Select an option

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)
}
}
@vnagendra

Copy link
Copy Markdown

@SinaMN75

Copy link
Copy Markdown

Awesome, Thanks.

@elyahk

elyahk commented Jan 15, 2022

Copy link
Copy Markdown

Awesome thanks

@ty-kim

ty-kim commented Nov 16, 2023

Copy link
Copy Markdown

Thank you so much

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