Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the X and Y of the edges of the screen in Swift

Tags:

ios

swift

I've wrote this code down here but it's not working the way I want, I have only got the random position in the all view, my meaning is to get random positions on the edges of the screen. How can I do it?

    let viewHeight = self.view!.bounds.height
    let viewWidth = self.view!.bounds.width

    randomYPosition = CGFloat(arc4random_uniform(UInt32(viewHeight)))
    randomXPosition = CGFloat(arc4random_uniform(UInt32(viewWidth)))
like image 888
David Dume Avatar asked Jan 18 '16 13:01

David Dume


2 Answers

Use the following property:

For Max:

view.frame.maxX
view.frame.maxY

For minimum:

view.frame.minX
view.frame.minY
like image 190
Ramesh_T Avatar answered Nov 06 '22 21:11

Ramesh_T


If you really want the bounds of the screen, then you should see How to get the screen width and height in iOS?, which tells you that you need to look at the UIScreen object for its dimensions. In Swift, the code works out to:

let screenRect = UIScreen.mainScreen().bounds
let screenWidth = screenRect.size.width
let screenHeight = screenRect.size.height

That really gives you the screen width and height, but it'd be strange if the screen origin weren't at (0,0). If you want to be sure, you can add the origin's coordinates:

let screenWidth = screenRect.size.width + screenRect.origin.x
let screenHeight = screenRect.size.height + screenRect.origin.y

All that said, there's usually little reason to look at the screen itself. With iOS now supporting split screen, your app may only be using part of the screen. It'd make more sense to look at the app's window, or even just at the view controller's view. Since these are both UIViews, they both have a bounds property just like any other view.

like image 22
Caleb Avatar answered Nov 06 '22 22:11

Caleb