在Objective-C中,我们可以使用以下代码获取设备的宽度和高度:
CGRect sizeRect = [UIScreen mainScreen].applicationFrame
float width = sizeRect.size.width
float height = sizeRect.size.height
Swift如何做到这一点?
在Objective-C中,我们可以使用以下代码获取设备的宽度和高度:
CGRect sizeRect = [UIScreen mainScreen].applicationFrame
float width = sizeRect.size.width
float height = sizeRect.size.height
Swift如何做到这一点?
Answers:
我没有尝试过,但是应该。
var bounds = UIScreen.main.bounds
var width = bounds.size.width
var height = bounds.size.height
斯威夫特4.2
let screenBounds = UIScreen.main.bounds
let width = screenBounds.width
let height = screenBounds.height
如果要在代码中使用它。干得好。
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")
}
}
var sizeRect = UIScreen.mainScreen().applicationFrame
var width = sizeRect.size.width
var height = sizeRect.size.height
正是这样,也对其进行了测试。
;
LOL XD
Swift
没有分号,然后再次出现,ObjectiveC
则可能会出现Ω(n)
编译错误LOL
UIScreen对象定义与基于硬件的显示关联的属性。iOS设备有一个主屏幕和零个或多个附加屏幕。每个屏幕对象都为关联的显示和其他有趣的属性定义了边界矩形
Apple Doc URL:
https://developer.apple.com/reference/uikit/uiwindow/1621597-screen
快速获取您用户设备的高度/宽度
let screenHeight = UIScreen.main.bounds.height
let screenWidth = UIScreen.main.bounds.width
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
}
这非常适合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")
}
}
applicationFrame
不提供屏幕尺寸。它给出了应用程序的大小。这是更好地使用bounds
,而不是applicationFrame
如果你想要的屏幕尺寸。