简体   繁体   English

如何将 activityIndicator 置于其父视图的中心?

[英]How to center activityIndicator to its superview?

I am facing issues with centering an activity indicator relative to the screen size and centered inside its superview.我在将活动指示器相对于屏幕尺寸居中并在其超级视图中居中时遇到问题。 This is how it's currently setup:这是它当前的设置方式:

self.activityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray)
self.tableBackgroundView.addSubview(self.activityIndicator)
self.activityIndicator.center.x = UIScreen.main.bounds.width / 2

The horizontal centering is great, but I'm trying to set the center.y to the table view's center.水平居中很好,但我试图将center.y设置为表格视图的中心。 What is the best way to set it to the center vertically in a way that will allow it to center for all screen sizes?以允许它在所有屏幕尺寸下居中的方式将它设置为垂直居中的最佳方法是什么? The image below shows it without a center.y being set explicitly下图显示了它没有明确设置center.y

在此处输入图像描述

The best way to center a UIActivityIndicatorView or in fact any view in the hierarchy is by using the NSLayoutConstraints, you can used them programmatically to center the ActivityIndicator like this.将 UIActivityIndi​​catorView 或实际上层次结构中的任何视图居中的最佳方法是使用 NSLayoutConstraints,您可以像这样以编程方式使用它们来居中 ActivityIndi​​cator。

activityIndicator = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray)

//This is important.
view.addSubview(activityIndicator)
//If the Activity Indicator is not in the correct z-index you can uncomment this line
//view.bringSubview(toFront: activityIndicator)

NSLayoutConstraint.activate([
    activityIndicator.centerXAnchor.constraint(equalTo: tableBackgroundView.centerXAnchor, constant: 0.0),
    activityIndicator.centerYAnchor.constraint(equalTo: tableBackgroundView.centerYAnchor, constant: 0.0)
])

Don't forget to add:不要忘记添加:

self.activityIndicator.translatesAutoresizingMaskIntoConstraints = false

In viewWillLayoutSubviews() method add this:viewWillLayoutSubviews()方法中添加:

NSLayoutConstraint.activate([
    activityIndicator.centerXAnchor.constraint(equalTo: tableBackgroundView.centerXAnchor, constant: 0.0),
    activityIndicator.centerYAnchor.constraint(equalTo: tableBackgroundView.centerYAnchor, constant: 0.0)
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM