如何获得设备的宽度和高度?

Div*_*iya 63 cocoa-touch ios uiscreen cgsize swift

在Objective-C中,我们可以使用以下代码获取设备宽度和高度:

CGRect sizeRect = [UIScreen mainScreen].applicationFrame
float width = sizeRect.size.width
float height = sizeRect.size.height
Run Code Online (Sandbox Code Playgroud)

怎么能用Swift做到这一点?

iPa*_*tel 128

我没试过,但应该是..

var bounds = UIScreen.main.bounds
var width = bounds.size.width
var height = bounds.size.height
Run Code Online (Sandbox Code Playgroud)

  • @Aks明确定义类型更安全,更可读. (2认同)

Pas*_*cal 19

@Houssni的回答是正确的,但既然我们正在谈论Swift,这个用例经常出现,可以考虑扩展CGRect类似于:

extension CGRect {
    var wh: (w: CGFloat, h: CGFloat) {
        return (size.width, size.height)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以使用它:

let (width, height) = UIScreen.mainScreen().applicationFrame.wh
Run Code Online (Sandbox Code Playgroud)

万岁!:)


Ada*_*aka 19

Swift 4.2

let screenBounds = UIScreen.main.bounds
let width = screenBounds.width
let height = screenBounds.height
Run Code Online (Sandbox Code Playgroud)


bpo*_*lat 14

如果你想在你的代码中使用它.干得好.

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")

    }


}
Run Code Online (Sandbox Code Playgroud)

  • @Jeff“不是 iPhone”XD (2认同)

h0u*_*sni 9

var sizeRect = UIScreen.mainScreen().applicationFrame
var width    = sizeRect.size.width
var height   = sizeRect.size.height
Run Code Online (Sandbox Code Playgroud)

正是这样,也测试了它.

  • 也没有`;`LOL XD (4认同)
  • @MatteoGobbi我考虑使用分号的良好做法......*使用它们.* (2认同)

Pau*_*lle 7

(Swift 3)请记住,大多数宽度和高度值将基于设备的当前方向.如果你想要一个不是基于旋转的一致值并且提供结果就像你在纵向旋转一样,那么试试一下fixedCoordinateSpace:

let screenSize = UIScreen.main.fixedCoordinateSpace.bounds
Run Code Online (Sandbox Code Playgroud)


jef*_*igy 5

由于您正在寻找设备屏幕尺寸,最简单的方法是:

let screenSize = UIScreen.mainScreen().bounds.size
let width = screenSize.width
let height = screenSize.height
Run Code Online (Sandbox Code Playgroud)


Pra*_*wad 5

这对于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")
        }
    }
Run Code Online (Sandbox Code Playgroud)