使用 Swift 中的 UIUserInterfaceIdiom 检测当前设备

swiftprogrammingmobile developmentiosiphone/ipad更新于 2025/11/25 15:34:00

要使用 iOS/Swift 检测当前设备,我们可以使用 UserInterfaceIdiom。它是 swift 中的一个枚举,用于指示正​​在使用哪个设备。

interface idiom 在其枚举中提供了多个值。

case unspecified
@available(iOS 3.2, *)
case phone // iPhone 和 iPod touch 样式 UI
@available(iOS 3.2, *)
case pad // iPad 样式 UI
@available(iOS 9.0, *)
case tv // Apple TV 样式 UI
@available(iOS 9.0, *)
case carPlay // CarPlay 样式 UI

在 swift 中,interfaceIdiom 可以按以下方式使用:

print(UIDevice.current.userInterfaceIdiom)
if UIDevice.current.userInterfaceIdiom == .phone {
    print("running on iPhone")
}

当我们在 iPhone 设备上运行上述代码时,将产生以下结果。



关于我们 | 隐私条款 | 学习路线
返回顶部