Updated 4 July 2023
Some times we need to perform some action on clicking the button , and we have to wait for some time for respective result.Generally we use loader in middle of screen after data will come we close the loader. we can also show the loader on that where we have clicked and when the data will come we stop the loader and set the default text on UIButton which was previously set.
For this we need to follow some steps:
1: Take UIButton from StoryBoard.
2: Now select UIButton , and click on “Show the identity Inspector”
3: Now In Class write the custom class Name “LoadingButton”
4: Now Define This Class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
class LoadingButton: UIButton { var originalButtonText: String? var activityIndicator: UIActivityIndicatorView! func showLoading() { originalButtonText = self.titleLabel?.text self.setTitle("", for: UIControlState.normal) if (activityIndicator == nil) { activityIndicator = createActivityIndicator() } showSpinning() } func hideLoading() { self.setTitle(originalButtonText, for: UIControlState.normal) activityIndicator.stopAnimating() } private func createActivityIndicator() -> UIActivityIndicatorView { let activityIndicator = UIActivityIndicatorView() activityIndicator.hidesWhenStopped = true activityIndicator.color = UIColor.white 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) } } |
5: Now its time to use :
1 |
@IBOutlet weak var fetchLocationBtn: LoadingButton! |
6: Crate the outlet as action of UIButton:
1 2 3 |
@IBAction func fetchLocationAction(_ sender: UIButton) { fetchLocationBtn.showLoading() } |
7: Now In this function you can use any kind of call or function, and when the result will come
Simply
1 |
self.fetchLocationBtn.hideLoading() |
8: When it will stop , it will showing the default title in button.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.