How to get device width and height?

后端 未结 12 1117
离开以前
离开以前 2020-12-23 14:13

In Objective-C we can get device width and height by using following code :

CGRect sizeRect = [UIScreen mainScreen].applicationFrame
float width = sizeRect.         


        
相关标签:
12条回答
  • 2020-12-23 15:03

    (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
    
    0 讨论(0)
  • 2020-12-23 15:06

    Swift 4.2

    let screenBounds = UIScreen.main.bounds
    let width = screenBounds.width
    let height = screenBounds.height
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-23 15:07

    @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! :)

    0 讨论(0)
  • 2020-12-23 15:15
     static func getDeviceType() -> String
        {
            var strDeviceType = ""
            if UIDevice().userInterfaceIdiom == .phone {
                switch UIScreen.main.nativeBounds.height {
                case 1136:
                    strDeviceType = "iPhone 5 or 5S or 5C"
                case 1334:
                    strDeviceType = "iPhone 6/6S/7/8"
                case 1920, 2208:
                    strDeviceType = "iPhone 6+/6S+/7+/8+"
                case 2436:
                    strDeviceType = "iPhone X"
                case 2688:
                    strDeviceType = "iPhone Xs Max"
                case 1792:
                    strDeviceType = "iPhone Xr"
                default:
                    strDeviceType = "unknown"
                }
            }
            return strDeviceType
        }
    
    0 讨论(0)
  • 2020-12-23 15:17

    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
    
    0 讨论(0)
提交回复
热议问题