Get iOS Screen Size In Swift

By Eddy Chung

To get the screen size in Swift, use the following code:

let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

print("The width is \(screenWidth) and the height is \(screenHeight)")
// For example, this will print:
// The width is 414.0 and the height is 896.0

Get Safe Area Size

The safe area is the the space between the top inset and the bottom inset. In this photo, it is the green colored part:

get ios screen size swift 2020 03 05 09 56 43

To get the size of the safe area use this code:

let window = UIApplication.shared.windows[0]
let safeFrame = window.safeAreaLayoutGuide.layoutFrame
let width = safeFrame.width
let height = safeFrame.height
print("The safe area width is \(width) and the safe area height is \(height)")
// For example, this will print:
// The safe area width is 414.0 and the safe area height is 818.0

To get the size of the insets (the red part in the above image), use this following code:

let window = UIApplication.shared.windows[0]
let topPadding = window.safeAreaInsets.top
let bottomPadding = window.safeAreaInsets.bottom
print("The top safe area is \(topPadding) and the bottom is \(bottomPadding)")
// For example, this will print:
// The top safe area is 44.0 and the bottom is 34.0
If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts