我们知道Apple Watch有两种屏幕尺寸:38mm和42mm . WKInterfaceDevice
类提供名为 screenBounds
的可读属性 . 我为 WKInterfaceDevice
编写了一个扩展,尝试添加一种方法来检测当前的设备类型 .
import WatchKit
enum WatchResolution {
case Watch38mm, Watch42mm
}
extension WKInterfaceDevice {
class func currentResolution() -> WatchResolution {
let watch38mmRect = CGRectMake(0.0, 0.0, 136.0, 170.0)
let watch42mmRect = CGRectMake(0.0, 0.0, 156.0, 195.0)
let currentBounds = WKInterfaceDevice.currentDevice().screenBounds
if CGRectEqualToRect(currentBounds, watch38mmRect) {
return WatchResolution.Watch38mm
} else {
return WatchResolution.Watch42mm
}
}
}
这是检测Apple Watch尺寸的正确方法吗?我在Apple文档中缺少另一种方法吗?
7 回答
Update Swift 4:
它包括新推出的Watch分辨率:
Usage
参考链接:Apple Developer Watch Interface Link
希望有所帮助....
谢谢
您的代码看起来不错,但有一些小问题:
您没有"unknown"屏幕大小的案例(可能在将来发布)
你正在使用
CGRectMake
但是在Swift中你应该使用CGRect
初始值设定项你正在使用
CGRectEqualToRect
但是在Swift中你可以使用==
或switch
你明确地返回
WatchResolution
枚举,但你不需要明确--Swift会从你的方法签名中找出它你宣布
watch42mmRect
但没有使用它我会像这样重写它:
你的方法看起来很好,没有任何问题 . 另一种解决方案是使用WKInterfaceController的contentFrame属性 . 如果宽度为312(156)像素,那么其42毫米也是38毫米 .
检查screenBounds似乎不再适用于带有真实设备的iOS 9的xCode 7,Watch 38mm返回的 Watch 大小始终为156x195 .
我(坏)的替代方法是根据视图结构检查viewcontroller contentFrame的宽度或高度
以上所有解决方案都运行良好 . 与screenBounds([[WKInterfaceDevice currentDevice] screenBounds])一起,也可以检查screenScale([[WKInterfaceDevice currentDevice] screenScale]) . 从这个意义上说,实际大小将是screenBounds * screenScale .
更多参考:https://developer.apple.com/watch/human-interface-guidelines/specifications/
对于Swift 4较短的例子: