Skip to content

Instantly share code, notes, and snippets.

@vnagendra
Forked from rajohns08/LoadingButton.swift
Last active August 25, 2022 07:39
Show Gist options
  • Save vnagendra/cd396af8135b059de0795589d8fcc39f to your computer and use it in GitHub Desktop.
Save vnagendra/cd396af8135b059de0795589d8fcc39f 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!
@IBInspectable
let activityIndicatorColor: UIColor = .lightGray
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 = activityIndicatorColor
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment