Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Screen size in Swift as Integer

Tags:

ios

swift

For positioning an element random in the screen but within the boundarys I need the resolution/screen size in swift. I already fount out how to get it with CGGraphics. Unfortunately I have to calculate a bit and need it as type UInt32, not CGFloat. I cannot use casting that way. Any ideas?

let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
//What I want to do
let screenHeight = screenSize.height-arc4random_uniform(screenSize.height)
like image 467
Zen5656 Avatar asked May 12 '15 11:05

Zen5656


1 Answers

If you want random X and Y positions for your element you can do something like this:

let screenSize = UIScreen.main.bounds
let randomXPos = CGFloat(arc4random_uniform(UInt32(screenSize.width)))
let randomYPos = CGFloat(arc4random_uniform(UInt32(screenSize.height)))

Swift 4.2

let screenSize = UIScreen.main.bounds
let randomXPos = CGFloat.random(in: 0..<screenSize.width)
let randomYPos = CGFloat.random(in: 0..<screenSize.height)
like image 143
Vasil Garov Avatar answered Sep 21 '22 15:09

Vasil Garov