How to get dimensions of current device screen?

How can my app get the dimensions of the screen?

Answered by ShinehahGnolaum in 302482022

I figured it out. I can addSubview to the navigationController property of the view controller.

KMT >> Why? What's the end goal?


An extremely relevant set of questions. Keep in mind that an app running on an iPad could easily be running in a split screen, so the dimensions available to the app aren't the dimensions of the screen.

I'm trying to figure out the best way to use an activity indicator view. It must be added to a view. I wondered if I should try to cover the entire screen with the activity indicator view. That would mean that there would have to be a view that I add the activity indicator view to that covers the entire screen. That counts out the main view of a view controller.

Or perhaps I can somehow dim the screen.

What do you get if you use the dimensions of the root view controller's parent UIWindow? I would expect that the window's dimensions are the largest area your app is allowed to draw into (which may or may not be the full screen).

I see addSubview as a method of UIWindow in the context helper, but I get an error that says "Instance member 'addSubview' cannot be used on type 'UIWindow'; did you mean to use a value of this type instead?", when I try to use addSubview(_:) with UIWindow.

Accepted Answer

I figured it out. I can addSubview to the navigationController property of the view controller.

>> I see addSubview as a method of UIWindow in the context helper, but I get an error that says "Instance member 'addSubview' cannot be used on type 'UIWindow'


You asked for the dimensions, not how to add a subview at the top level. 🙂


Using the navigationController property seems kind of hinky, unless you are in fact embedding a navigator controller. You should be able to go from UIWindow to the (root) view controller, and add a subview to its view.

Good, thanks for the followup, good luck w/your app and pls. do a favor by marking your answer as the solution, and see if you can remember to flesh out your questions in the future 😉

Code Block
var PT: CGFloat = 0;
override func viewDidLoad() {
super.viewDidLoad()
setPoints();
}
func setPoints() {
let screenBounds = UIScreen.main.bounds
let screenScale = UIScreen.main.scale
let screenSize = CGSize(width: screenBounds.size.width * screenScale, height: screenBounds.size.height * screenScale)
let nativeBounds = UIScreen.main.nativeBounds
let nativeScale = UIScreen.main.nativeScale
let pxScreenWidth:CGFloat = nativeBounds.width;
let ptScreenWidth:CGFloat = screenBounds.width;
PT = pxScreenWidth/ptScreenWidth/nativeScale;
}


How to use:
Code Block
let label: UILabel = UILabel(frame: CGRect(x: 15 * PT, y: 10 * PT, width: self.view.frame.width - 30 * PT, height: self.view.frame.height - 20 * PT))


How to get dimensions of current device screen?
 
 
Q