简体   繁体   English

如何使用 SwiftUI 检测当前设备?

[英]How to detect current device using SwiftUI?

I am trying to determine whether the device being used is iPhone or iPad.我正在尝试确定正在使用的设备是 iPhone 还是 iPad。

Please see this question: Detect current device with UI_USER_INTERFACE_IDIOM() in Swift请看这个问题: Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

That solution works if you use UIKit. But如果您使用 UIKit,则该解决方案有效。但是

What is the equivalent method if you are using SwiftUI?如果您使用 SwiftUI,等效方法是什么?

you can find the device type, like this:您可以找到设备类型,如下所示:

if UIDevice.current.userInterfaceIdiom == .pad {

    }

You can use this:你可以使用这个:

UIDevice.current.localizedModel

In your case, an implementation method could be:在您的情况下,实现方法可能是:

if UIDevice.current.localizedModel == "iPhone" {
     print("This is an iPhone")
} else if UIDevice.current.localizedModel == "iPad" {
     print("This is an iPad")
}

Obviously, you can use this for string interpolation such as this (assuming the current device type is an iPhone):显然,您可以将其用于字符串插值,例如(假设当前设备类型是 iPhone):

HStack {
     Text("Device Type: ")
     Text(UIDevice.current.localizedModel)
}

//Output:
//"Device Type: iPhone"

It will return the device type.它将返回设备类型。 (iPhone, iPad, AppleWatch) No further imports are necessary aside from SwiftUI which should have already been imported upon creation of your project if you selected SwiftUI as the interface. (iPhone、iPad、AppleWatch)除了 SwiftUI 之外,如果您选择 SwiftUI 作为接口,则在创建项目时应该已经导入了其他导入。

NOTE: It does not return the device model (despite the ".localizedModel")注意:它不会返回设备 model(尽管有“.localizedModel”)

Hope this helps!希望这可以帮助!

UIDevice is no longer available from WatchKit 2 on UIDevice 在 WatchKit 2 上不再可用

WKInterfaceDevice could be helpful: https://developer.apple.com/documentation/watchkit/wkinterfacedevice WKInterfaceDevice可能会有帮助: https://developer.apple.com/documentation/watchkit/wkinterfacedevice

ie: IE:

let systemName = WKInterfaceDevice.current().systemName
let systemVersion = WKInterfaceDevice.current().systemVersion
let deviceModel = WKInterfaceDevice.current().model

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM