Skip to content

Instantly share code, notes, and snippets.

@jalopezsuarez
Last active August 27, 2018 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jalopezsuarez/0ecc885b3fd5c555630799a067d66d98 to your computer and use it in GitHub Desktop.
Save jalopezsuarez/0ecc885b3fd5c555630799a067d66d98 to your computer and use it in GitHub Desktop.
Display activity indicator inside UIButton Swift4
//
// UIButtonActivity.swift
// Extensions
//
// Created by Jose Antonio Lopez on 27/08/2018.
// Copyright © 2018 Jose Antonio Lopez <jalopezsuarez@gmail.com>. All rights reserved.
//
import Foundation
import UIKit
class UIButtonActivity: UIButton {
@IBInspectable var indicatorColor : UIColor = .lightGray
private var buttonLabel: String?
func startAnimating() {
self.isEnabled = false
buttonLabel = self.titleLabel?.text
self.setTitle("", for: .normal)
let indicator = UIActivityIndicatorView()
indicator.color = indicatorColor
indicator.hidesWhenStopped = true
let buttonHeight = self.bounds.size.height
let buttonWidth = self.bounds.size.width
indicator.center = CGPoint(x: buttonWidth/2, y: buttonHeight/2)
let scale = max(min((self.frame.size.height - 4) / 21, 2.0), 0.0)
let transform: CGAffineTransform = CGAffineTransform(scaleX: scale, y: scale)
indicator.transform = transform
self.addSubview(indicator)
indicator.startAnimating()
}
func stopAnimating() {
self.isEnabled = true
if let titleLabel = buttonLabel {
self.setTitle(titleLabel, for: .normal)
}
if let indicator = self.viewWithTag(tag) as? UIActivityIndicatorView {
indicator.stopAnimating()
indicator.removeFromSuperview()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment