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

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

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

在Swift中如何做到这一点?

我没有尝试,但应该是..

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

@Houssni的回答是正确的,但是由于我们正在谈论Swift,而且这个用CGRect经常出现,所以我们可以考虑扩展CGRect就像这样:

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

那么你可以像这样使用它:

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

万岁! 🙂

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

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

斯威夫特4

 let screenBounds = UIScreen.main.bounds let width = screenBounds.width let height = screenBounds.height 
 var sizeRect = UIScreen.mainScreen().applicationFrame var width = sizeRect.size.width var height = sizeRect.size.height 

完全像这样,也testing了它。

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

 let screenSize = UIScreen.main.fixedCoordinateSpace.bounds 

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

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

@Adam Smaka的回答很接近,在Swift 3中是这样的:

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

UIScreen对象定义与基于硬件的显示相关的属性。 iOS设备有一个主屏幕和零个或多个连接的屏幕。 每个屏幕对象为关联的显示和其他有趣的属性定义边界矩形

Apple Doc URL:

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

用swift 3.0获得你的用户设备的高度/宽度

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