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. 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
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.
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:
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: tableBackgroundView.centerXAnchor, constant: 0.0),
activityIndicator.centerYAnchor.constraint(equalTo: tableBackgroundView.centerYAnchor, constant: 0.0)
])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.