Display activity indicator inside UIButton

后端 未结 10 1719
囚心锁ツ
囚心锁ツ 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:10

    Swift 5, Xcode 11.3

    I've modified it for my use case to include the button text, together with the spinner

    import UIKit
    
    class LoadingButton: UIButton {
    
    var activityIndicator: UIActivityIndicatorView!
    
    let activityIndicatorColor: UIColor = .gray
    
    func loadIndicator(_ shouldShow: Bool) {
        if shouldShow {
            if (activityIndicator == nil) {
                activityIndicator = createActivityIndicator()
            }
            self.isEnabled = false
            self.alpha = 0.7
            showSpinning()
        } else {
            activityIndicator.stopAnimating()
            self.isEnabled = true
            self.alpha = 1.0
        }
    }
    
    private func createActivityIndicator() -> UIActivityIndicatorView {
        let activityIndicator = UIActivityIndicatorView()
        activityIndicator.hidesWhenStopped = true
        activityIndicator.color = activityIndicatorColor
        return activityIndicator
    }
    
    private func showSpinning() {
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(activityIndicator)
        positionActivityIndicatorInButton()
        activityIndicator.startAnimating()
    }
    
    private func positionActivityIndicatorInButton() {
        let trailingConstraint = NSLayoutConstraint(item: self,
                                                   attribute: .trailing,
                                                   relatedBy: .equal,
                                                   toItem: activityIndicator,
                                                   attribute: .trailing,
                                                   multiplier: 1, constant: 16)
        self.addConstraint(trailingConstraint)
    
        let yCenterConstraint = NSLayoutConstraint(item: self,
                                                   attribute: .centerY,
                                                   relatedBy: .equal,
                                                   toItem: activityIndicator,
                                                   attribute: .centerY,
                                                   multiplier: 1, constant: 0)
        self.addConstraint(yCenterConstraint)
    }
    
    }
    

    If you're using storyboard, ensure that your button is of type LoadingButton (do this on your storyboard as well as view controller file, otherwise it'll crash)

    @IBOutlet weak var myButton: LoadingButton!
    

    and to use it,

    myButton.loadIndicator(true)
    

提交回复
热议问题