Skip to content

Instantly share code, notes, and snippets.

@vinczebalazs
Last active January 29, 2020 12:27
Show Gist options
  • Save vinczebalazs/36e11225c33aa9a896cd9c35d7101ea0 to your computer and use it in GitHub Desktop.
Save vinczebalazs/36e11225c33aa9a896cd9c35d7101ea0 to your computer and use it in GitHub Desktop.
A UIButton subclass which can display a loading spinner instead of its title.
import UIKit
class LoadingButton: UIButton {
// MARK: Public Properties
var spinnerSpeed = 0.75
var spinnerWidth: CGFloat = 4
var spinnerRadius = 30
var isSpinnerRounded = true
var isLoading: Bool { _isLoading }
// MARK: Private Properties
private var _isLoading = false
private lazy var spinner: LoadingSpinner = {
LoadingSpinner(frame: CGRect(x: 0, y: 0, width: spinnerRadius, height: spinnerRadius), speed: spinnerSpeed,
color: tintColor, width: spinnerWidth, isRounded: isSpinnerRounded)
}()
// MARK: Functions
override func awakeFromNib() {
super.awakeFromNib()
addSubview(spinner)
spinner.alpha = 0
}
override func layoutSubviews() {
super.layoutSubviews()
spinner.center = CGPoint(x: frame.width / 2, y: frame.height / 2)
}
func startLoading() {
if isLoading { return }
isEnabled = false
alpha = 1.0
_isLoading = true
// Fade the title, image and the loading spinner.
spinner.alpha = 0
spinner.start()
UIView.animate(withDuration: 0.25, animations: {
self.spinner.alpha = 1
self.titleLabel?.alpha = 0
})
}
func stopLoading() {
if !isLoading { return }
isEnabled = true
_isLoading = false
// Fade the title, image and the loading spinner.
UIView.animate(withDuration: 0.25, animations: {
self.spinner.alpha = 0
self.titleLabel?.alpha = 1
self.imageView?.alpha = 1
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment