Skip to content

Instantly share code, notes, and snippets.

@vdugnist
Created October 11, 2023 16:28
Show Gist options
  • Save vdugnist/267f773394f65f115d4bf0df4970e44b to your computer and use it in GitHub Desktop.
Save vdugnist/267f773394f65f115d4bf0df4970e44b to your computer and use it in GitHub Desktop.
UIButton extension that allows replacing button with a loading indicator and back with one line of code
import UIKit
extension UIButton {
func hideButtonAndShowSpinner() {
self.isHidden = true
let spinnerTag = Int(bitPattern: Unmanaged.passUnretained(self).toOpaque())
if self.superview?.subviews.first(where: { (view) -> Bool in
return view.isKind(of: UIActivityIndicatorView.self) && view.tag == spinnerTag
}) != nil {
return
}
let spinner = UIActivityIndicatorView(style: .medium)
spinner.tag = spinnerTag
spinner.startAnimating()
spinner.center = self.center
self.superview?.addSubview(spinner)
spinner.snp.makeConstraints { (make) in
make.center.equalTo(self)
}
}
func hideSpinnerAndShowButton() {
let spinnerTag = Int(bitPattern: Unmanaged.passUnretained(self).toOpaque())
let spinner = self.superview?.subviews.first(where: { (view) -> Bool in
return view.isKind(of: UIActivityIndicatorView.self) && view.tag == spinnerTag
})
spinner?.removeFromSuperview()
self.isHidden = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment