Display activity indicator inside UIButton

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

    Here is my edit with little less code.

    class Button: UIButton {
        private var originalButtonText: String?
    
        private lazy var activityIndicator: UIActivityIndicatorView = {
            let activityIndicator = UIActivityIndicatorView()
            activityIndicator.translatesAutoresizingMaskIntoConstraints = false
            activityIndicator.color = .black
            addSubview(activityIndicator)
    
            NSLayoutConstraint.activate([
                activityIndicator.centerYAnchor.constraint(equalTo: self.centerYAnchor),
                activityIndicator.centerXAnchor.constraint(equalTo: self.centerXAnchor)
            ])
    
            return activityIndicator
        }()
    
        func loading(_ isLoading: Bool) {
            isEnabled = !isLoading
    
            if isLoading {
                originalButtonText = titleLabel?.text
                setTitle("", for: .normal)
                activityIndicator.startAnimating()
            } else {
                setTitle(originalButtonText, for: .normal)
                activityIndicator.stopAnimating()
            }
        }
    }
    

    Usage: button.loading(true/false)

提交回复
热议问题