Xcode: How to get the screen size of iOS device?

With the below code, you can get the screen size of any iOS device and calculate additional relative values, such as “half of the screen”. For this purpose we will use UIScreen.main.bounds

Relative positioning of screen elements is particular useful and important due to the variety of iPhone and iPad screen sizes being used. With this approach you do not need to worry about the size of your user’s screen, your on-screen objects will always be relative to their screen.

For example, you can create a MapView object, and force this object to always occupy the upper half of the screen, not less and not more. In this case, your best approach would be to:

  1. Capture the screen size and store in a variable, as seen in the above code
  2. Calculate the half of that value and store in a second variable (Step 1 & 2 can be combined and optimized)
  3. Create the MapView components
  4. Manipulate the heigh constraint with the help of the variable in Step 2

Hope this is helpful. Happy coding!