How to get device width and height?

断了今生、忘了曾经 提交于 2019-11-29 20:50:17
iPatel

I haven't tried but it should be..

var bounds = UIScreen.main.bounds
var width = bounds.size.width
var height = bounds.size.height

@Houssni 's answer is correct, but since we're talking Swift and this use case will come up often, one could consider extending CGRect similar to this:

extension CGRect {
    var wh: (w: CGFloat, h: CGFloat) {
        return (size.width, size.height)
    }
}

Then you can use it like:

let (width, height) = UIScreen.mainScreen().applicationFrame.wh

Hooray! :)

Swift 4.2

let screenBounds = UIScreen.main.bounds
let width = screenBounds.width
let height = screenBounds.height

If you want to use it in your code. Here you go.

func iPhoneScreenSizes(){
    let bounds = UIScreen.mainScreen().bounds
    let height = bounds.size.height

    switch height {
    case 480.0:
        print("iPhone 3,4")
    case 568.0:
        print("iPhone 5")
    case 667.0:
        print("iPhone 6")
    case 736.0:
        print("iPhone 6+")

    default:
        print("not an iPhone")

    }


}
var sizeRect = UIScreen.mainScreen().applicationFrame
var width    = sizeRect.size.width
var height   = sizeRect.size.height

Exactly like this, tested it also.

(Swift 3) Keep in mind that most width and height values will be based on device's current orientation. If you want a consistent value that is not based on rotation and offers results as if you were in a portrait-up rotation, give fixedCoordinateSpace a try:

let screenSize = UIScreen.main.fixedCoordinateSpace.bounds

Since you're looking for the device screen size the simplest way is:

let screenSize = UIScreen.mainScreen().bounds.size
let width = screenSize.width
let height = screenSize.height

While @Adam Smaka's answer was close, in Swift 3 it is the following:

let screenBounds = UIScreen.main.bounds
let width = screenBounds.width
let height = screenBounds.height

A UIScreen object defines the properties associated with a hardware-based display. iOS devices have a main screen and zero or more attached screens. Each screen object defines the bounds rectangle for the associated display and other interesting properties

Apple Doc URL :

https://developer.apple.com/reference/uikit/uiwindow/1621597-screen

To get Height/width of ur user's device with swift 3.0

let screenHeight = UIScreen.main.bounds.height
let screenWidth = UIScreen.main.bounds.width

In Swift 4 I had to use NSScreen.main?.deviceDescription

let deviceDescription = NSScreen.main?.deviceDescription          
let screenSize = deviceDescription![.size]
let screenHeight = (screenSize as! NSSize).height
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!