Display activity indicator inside UIButton

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

    Swift 4:

    extension UIButton {
        func loadingIndicator(_ show: Bool) {
            let tag = 808404
            if show {
                self.isEnabled = false
                self.alpha = 0.5
                let indicator = UIActivityIndicatorView()
                let buttonHeight = self.bounds.size.height
                let buttonWidth = self.bounds.size.width
                indicator.center = CGPoint(x: buttonWidth/2, y: buttonHeight/2)
                indicator.tag = tag
                self.addSubview(indicator)
                indicator.startAnimating()
            } else {
                self.isEnabled = true
                self.alpha = 1.0
                if let indicator = self.viewWithTag(tag) as? UIActivityIndicatorView {
                    indicator.stopAnimating()
                    indicator.removeFromSuperview()
                }
            }
        }
    }
    

    Usage: button.loadingIndicator(true/false)

提交回复
热议问题