Z-Tech Z-Tech - 1 year ago 150
Swift Question

Swift: Determine iOS Screen size

I would like to use Swift code to properly position items in my app for no matter what the screen size is. For example, if I want a button to be 75% of the screen wide, I could do something like

(screenWidth * .75)
to be the width of the button. I have found that this could be determined in Objective-C by doing

CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;

Unfortunately, I am unsure of how to convert this to Swift. Does anyone have an idea?


Answer Source

Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download