简体   繁体   中英

Center a UIActivityIndicatorView for a UITableViewController in the window, not in the table view

I have a UIActivityIndicatorView to my table view in the interface designer. I am trying to center it in the middle of the screens using the following:

   override func viewWillLayoutSubviews() {
        self.activityView.center = self.view.center
    }

But it always seems to be sitting too 'low' on the page, it appears to be centered in the middle of the UITableView, not in the middle of the window like I want (ie. It is getting pushed down by the navigation bar etc)

The solution was to set the activityView frame to the bounds of the view. Setting just the center doesn't work because the y value for the tableView frame is negative.

override func viewWillLayoutSubviews() {
    self.activityView.translatesAutoresizingMaskIntoConstraints = true
    self.activityView.frame = self.view.bounds
}

Using auto layout, you can use layoutMarginsGuide to get the right center X, Y anchor in both UITableView s and UICollectionView s:

activityView.translatesAutoresizingMaskIntoConstraints = false
activityView.centerXAnchor.constraint(equalTo: view.layoutMarginsGuide.centerXAnchor).isActive = true
activityView.centerYAnchor.constraint(equalTo: view.layoutMarginsGuide.centerYAnchor).isActive = true

Have you tried:

  self.activityView.center = self.view.window?.center

If not then how about this:

let screenSize = UIScreen.main.bounds
self.activityView.center = CGPoint(x: screenSize.width / 2, y: screenSize.height / 2)

It's a bit longer but handles In-Call Status Bar well.

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.

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