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)))
Use the following property:
For Max:
view.frame.maxX
view.frame.maxY
For minimum:
view.frame.minX
view.frame.minY
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 UIView
s, they both have a bounds
property just like any other view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With