How to get device width and height?

后端 未结 12 1116
离开以前
离开以前 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 14:52
    var sizeRect = UIScreen.mainScreen().applicationFrame
    var width    = sizeRect.size.width
    var height   = sizeRect.size.height
    

    Exactly like this, tested it also.

    0 讨论(0)
  • 2020-12-23 14:53

    This works great for Xcode 12

    func iPhoneScreenSizes() {
            let height = UIScreen.main.bounds.size.height
            switch height {
            case 480.0:
                print("iPhone 3,4")
            case 568.0:
                print("iPhone 5 | iPod touch(7th gen)")
            case 667.0:
                print("iPhone 6 | iPhone SE(2nd gen) | iPhone 8")
            case 736.0:
                print("iPhone 6+ | iPhone 8+")
            case 812.0:
                print("iPhone X | iPhone XS | iPhone 11 Pro")
            case 896.0:
                print("iPhone XR | iPhone XS Max | iPhone 11 | iPhone 11 Pro Max")
            default:
                print("not an iPhone")
            }
        }
    
    0 讨论(0)
  • 2020-12-23 14:55

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

    I haven't tried but it should be..

    var bounds = UIScreen.main.bounds
    var width = bounds.size.width
    var height = bounds.size.height
    
    0 讨论(0)
  • 2020-12-23 14:58

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

    func iPhoneScreenSizes() {
        let bounds = UIScreen.main.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+")
        case 812.0:
            print("iPhone X")
            print("iPhone XS")
            break
        case 896.0:
            print("iPhone XR")
            print("iPhone XS Max")
            break
        default:
            print("not an iPhone")
    
        }
    }
    
    0 讨论(0)
  • 2020-12-23 15:00

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