将UIButton中的ActivityIndi​​catorView居中时出现问题

时间:2019-07-13 21:56:01

标签: ios layout uibutton center uiactivityindicatorview

我正在尝试使用约束以编程方式将UIActivityIndi​​catorView居中于UIButton中,但是它不起作用。 注意:如果您旋转设备,它将居中!

enter image description here

我正在使用的代码是

func animateButton(shouldLoad: Bool, with message: String) {


    self.isUserInteractionEnabled = !shouldLoad

    // Should start loading
    if shouldLoad {

        self.setTitle("", for: .normal)

        UIView.animate(withDuration: 0.2, animations: { 
            self.layer.cornerRadius = self.frame.height / 2
            self.frame = CGRect(x: self.frame.midX - self.frame.height / 2, y: self.frame.origin.y, width: self.frame.height, height: self.frame.height)
        }, completion: { (done) in
            if done {
                self.showLoading()
                UIView.animate(withDuration: 0.2, animations: {
                    self.spinner.alpha = 1
                    self.layoutIfNeeded()
                })
            }
        })

    // Should end loading
    } else {

        self.setTitle(message, for: .normal)

        for subview in self.subviews {
            if subview == spinner {
                subview.removeFromSuperview()
            }
        }

        UIView.animate(withDuration: 0.2, animations: { 
            self.layer.cornerRadius = 5
            self.frame = self.originalFrame!
        })

    }

}

func showLoading() {
    if (spinner == nil) {
        spinner = createSpinner()
    }

    self.addSubview(spinner)
    centerActivityIndicatorInButton()
    spinner.startAnimating()
}

func hideLoading() {
    spinner.stopAnimating()
}

private func createSpinner() -> UIActivityIndicatorView {
    let activityIndicator = UIActivityIndicatorView()
    activityIndicator.activityIndicatorViewStyle = .whiteLarge
    activityIndicator.color = UIColor.darkGray
    activityIndicator.alpha = 0
    activityIndicator.hidesWhenStopped = true

    return activityIndicator
}

private func centerActivityIndicatorInButton() {
    spinner.translatesAutoresizingMaskIntoConstraints = false

    let xCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: spinner, attribute: .centerX, multiplier: 1, constant: 0)
    self.addConstraint(xCenterConstraint)

    let yCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: spinner, attribute: .centerY, multiplier: 1, constant: 0)
    self.addConstraint(yCenterConstraint)
}

在使用此代码手动计算中心的情况下它可以工作。但是在旋转的情况下,它不起作用,也不是100%准确,因为我们需要在宽度和高度上添加1点

let buttonHeight = self.bounds.size.height
let buttonWidth = self.bounds.size.width
spinner.center = CGPoint(x: buttonWidth/2, y: buttonHeight/2)

提前感谢您的时间

0 个答案:

没有答案