4

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()
}

}
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256
  • You need to add the subview to the root view controller – OverD Aug 05 '17 at 13:09
  • The way you worded this, it sounds like you wish to have the iPad "window" or "screen", when in "split view" mode - showing *two* apps - have a subview in the center of this "window". In other words, a subview spanning over two apps? That can't happen. OTOH, if what you want is to center a subview inside of *your* app, simply set two constraints - the centerX and centerX anchors to it's superview. –  Aug 05 '17 at 13:45

2 Answers2

4

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
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
  • @Jeffrey Thomas thanks! I actually used this first (I didn't include it in the question) but my mistake was a lot deeper which was causing the error. Anyway thanks! – Lance Samaria Aug 05 '17 at 16:31
1

Window is subclass of UIView. Just add it as it's subview like you're adding a view to another view. But remember that window is shared throughout your app, so adding it every-time will consume memory, remove it after your job is done. If you want to center it in the window, you can use autoResizingMask or add constraints to it.

farzadshbfn
  • 2,710
  • 1
  • 18
  • 38