Display activity indicator inside UIButton

后端 未结 10 1704
囚心锁ツ
囚心锁ツ 2021-01-31 17:36

I would like to change the content of a UIButton to an ActivityIndicator after it is pressed.

I know buttons have an imageView and a titleLabel, but I don\'t know how to

10条回答
  •  囚心锁ツ
    2021-01-31 18:05

    Updated selected answer( steve-rosenberg ) for Apple Swift version 3.0.1 (swiftlang-800.0.58.6 clang-800.0.42.1) Xcode 8.1 (8B62)

    import ObjectiveC
    
    private var originalButtonText: String?
    private var activityIndicator: UIActivityIndicatorView!
    
    extension UIButton{
    
        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 = UIColor.lightGray
            return activityIndicator
        }
    
        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)
        }
    }
    

提交回复
热议问题