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()
}
}
}
}