swiftcenteringsubviewuiwindowuiscreen

Swift iOS -How to Add Subview to Window's Center?


I have an activity indicator that gets presented on an iPhone and iPad. In the iPad in split screen mode it gets presented to whichever side of the view that called it. I would instead like it to get presented in the middle/center the window's screen. If I do it this way wether on the iPhone in portrait or iPad in split screen mode it will always be in the center of the screen.

How do I do this?

MyView: UIViewController{

let actInd = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)


@IBAction fileprivate func buttonPressed(_ sender: UIButton) {

      guard let window = UIApplication.shared.keyWindow else { return }
      //how to add actInd as subview to the window' screen?
      actInd.startAnimating()
}

}

Solution

  • It's pretty simple. Turn off the auto-resizing mask. Add the add actInd to window, then set the center anchors.

    actInd.translatesAutoresizingMaskIntoConstraints = false
    
    window.addSubview(actInd)
    actInd.centerXAnchor.constraint(equalTo: window.centerXAnchor).isActive = true
    actInd.centerYAnchor.constraint(equalTo: window.centerYAnchor).isActive = true