[英]How to detect current device using SwiftUI?
我正在尝试确定正在使用的设备是 iPhone 还是 iPad。
请看这个问题: Detect current device with UI_USER_INTERFACE_IDIOM() in Swift
如果您使用 UIKit,则该解决方案有效。但是
如果您使用 SwiftUI,等效方法是什么?
您可以找到设备类型,如下所示:
if UIDevice.current.userInterfaceIdiom == .pad {
}
你可以使用这个:
UIDevice.current.localizedModel
在您的情况下,实现方法可能是:
if UIDevice.current.localizedModel == "iPhone" {
print("This is an iPhone")
} else if UIDevice.current.localizedModel == "iPad" {
print("This is an iPad")
}
显然,您可以将其用于字符串插值,例如(假设当前设备类型是 iPhone):
HStack {
Text("Device Type: ")
Text(UIDevice.current.localizedModel)
}
//Output:
//"Device Type: iPhone"
它将返回设备类型。 (iPhone、iPad、AppleWatch)除了 SwiftUI 之外,如果您选择 SwiftUI 作为接口,则在创建项目时应该已经导入了其他导入。
注意:它不会返回设备 model(尽管有“.localizedModel”)
希望这可以帮助!
UIDevice 在 WatchKit 2 上不再可用
WKInterfaceDevice可能会有帮助: https://developer.apple.com/documentation/watchkit/wkinterfacedevice
IE:
let systemName = WKInterfaceDevice.current().systemName
let systemVersion = WKInterfaceDevice.current().systemVersion
let deviceModel = WKInterfaceDevice.current().model
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.