我正在使用约束使 UIButton 内的指示器居中。调整@DanielQ 的扩展,变成:
extension UIButton {
func loadingIndicator(show: Bool) {
let tag = 9876
if show {
let indicator = UIActivityIndicatorView()
indicator.tag = tag
self.addSubview(indicator)
indicator.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let verticalConstraint = NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
self.addConstraints([horizontalConstraint, verticalConstraint])
indicator.startAnimating()
} else {
if let indicator = self.viewWithTag(tag) as? UIActivityIndicatorView {
indicator.stopAnimating()
indicator.removeFromSuperview()
}
}
}
}