我正在尝试确定正在使用的设备是 iPhone 还是 iPad。
请看这个问题:Detect current device with UI_USER_INTERFACE_IDIOM() in Swift
如果您使用 UIKit,该解决方案有效。但
如果您使用的是 SwiftUI,那么等效的方法是什么?
您可以找到设备类型,如下所示:
if UIDevice.current.userInterfaceIdiom == .pad {
}
Run Code Online (Sandbox Code Playgroud)
你可以使用这个:
UIDevice.current.localizedModel
Run Code Online (Sandbox Code Playgroud)
对于您的情况,实现方法可以是:
if UIDevice.current.localizedModel == "iPhone" {
print("This is an iPhone")
} else if UIDevice.current.localizedModel == "iPad" {
print("This is an iPad")
}
Run Code Online (Sandbox Code Playgroud)
显然,您可以使用它进行字符串插值,如下所示(假设当前设备类型是 iPhone):
HStack {
Text("Device Type: ")
Text(UIDevice.current.localizedModel)
}
//Output:
//"Device Type: iPhone"
Run Code Online (Sandbox Code Playgroud)
它将返回设备类型。(iPhone、iPad、AppleWatch)除了 SwiftUI 之外,不需要进一步导入,如果您选择 SwiftUI 作为界面,则在创建项目时应该已经导入了 SwiftUI。
注意:它不会返回设备模型(尽管有“.localizedModel”)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
3791 次 |
| 最近记录: |