traitCollection.userInterfaceIdiom return -1



我想检查iPhone或iPad是否使用这些代码

if traitCollection.userInterfaceIdiom == UIUserInterfaceIdiom.Phone {
    println("iPhone")
} else {
    println("iPad")
}

我尝试使用iPhone模拟器和我的iPhone,但它打印"iPad"

然后我尝试打印"traitCollection.userInterfaceIdiom"

println(traitCollection.userInterfaceIdiom.rawValue)

它打印"-1"而不是"0"(iPhone)或"1"(iPad)

我不知道问题出在哪里,我一直在谷歌上搜索,但没有找到这里发生的事情。

你做对了。我将您的代码直接复制并粘贴到应用程序中,就像您拥有的那样:

if traitCollection.userInterfaceIdiom == UIUserInterfaceIdiom.Phone {
    println("iPhone")
} else {
    println("iPad")
}

在iPhone模拟器中,我在控制台中看到iPhone。在iPad模拟器中,我在控制台中看到iPad

您可能只是在错误的时间运行此代码。请记住,除非您的视图在界面中,否则不会设置您的特征集合。如果您想在其他时间检查,请询问UIDevice.currentDevice(),而不是特征集合,有关userInterfaceIdiom

在视图出现之前,特征集合属性是未知的。

来自苹果的文档:

  • UIUserInterfaceIdiomUnspecified

当对象具有特征集合,但尚未在环境中时使用。例如,已创建但未放入视图层次结构中的视图。

相关内容

最新更新