如何以编程方式在 Swift 中将 UIActivityIndi​​catorView 居中?

How do I center a UIActivityIndicatorView programmatically in Swift?

我想以编程方式将 activity 指示器放置在 table 视图控制器的中央,但是当我 运行 我的代码时,它总是出现在左上角。

这是我的 swift 代码;

let activityIndicator: UIActivityIndicatorView = {
    let activityIndicator = UIActivityIndicatorView()
    activityIndicator.style = .large
    activityIndicator.hidesWhenStopped = true
    activityIndicator.color = .white
    activityIndicator.startAnimating()
    return activityIndicator
}()

tableView.addSubview(activityIndicator)
    
NSLayoutConstraint.activate([
    activityIndicator.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
    activityIndicator.centerYAnchor.constraint(equalTo: tableView.centerYAnchor)
])
    
tableView.layoutSubviews()

你需要设置activityIndicator.translatesAutoresizingMaskIntoConstraints = false

  lazy var activityIndicator: UIActivityIndicatorView = {
    let activityIndicator = UIActivityIndicatorView()
    activityIndicator.style = .large
    activityIndicator.translatesAutoresizingMaskIntoConstraints = false
    activityIndicator.hidesWhenStopped = true
    activityIndicator.color = .white
    activityIndicator.startAnimating()
    return activityIndicator
}()

我需要包含该行;

activityIndicator.translatesAutoresizingMaskIntoConstraints = false