如何在iOS 8.3中检测设备是否为iPad?

Ben*_*ero 6 xcode ipad ios ios8.3

我们将SDK更新到iOS 8.3,突然之间,我们的iPad检测方法无法正常工作:

+ (BOOL) isiPad
{
#ifdef UI_USER_INTERFACE_IDIOM
    return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
#endif
    return NO;
}
Run Code Online (Sandbox Code Playgroud)

ifdef永远不会输入该块,因此return NO;始终运行.如何在不使用设备的情况下检测设备是否为iPad UI_USER_INTERFACE_IDIOM()


我正在使用:

  • Xcode 6.3(6D570)
  • iOS 8.2(12D508) - 使用iOS 8.3编译器进行编译
  • 部署:目标设备系列:iPhone/iPad
  • Mac OS X:约塞米蒂(10.10.3)
  • Mac:MacBook Pro(MacBookPro11,3)

War*_*ton 12

8.2 UserInterfaceIdiom()

#define UI_USER_INTERFACE_IDIOM() ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? [[UIDevice currentDevice] userInterfaceIdiom] : UIUserInterfaceIdiomPhone)
Run Code Online (Sandbox Code Playgroud)

8.3 UserInterfaceIdiom()

static inline UIUserInterfaceIdiom UI_USER_INTERFACE_IDIOM() {
    return ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ?
            [[UIDevice currentDevice] userInterfaceIdiom] :
            UIUserInterfaceIdiomPhone);
}
Run Code Online (Sandbox Code Playgroud)

所以#ifdef UI_USER_INTERFACE_IDIOM总是假的8.3

请注意标题说

提供了UI_USER_INTERFACE_IDIOM()函数,以便在部署到小于3.2的iOS版本时使用.如果您要部署的最早版本的iPhone/iOS是3.2或更高版本,您可以直接使用 - [UIDevice userInterfaceIdiom].

所以建议你重构一下

+ (BOOL) isiPad
{
    static BOOL isIPad = NO;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        isIPad = [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;
    });
    return isIPad;
}
Run Code Online (Sandbox Code Playgroud)

  • 不需要仅计算一次该值.它只是便宜一次,因为iPad在运行时中途通常不会成为iPhone.所以是的,`#define`如果它适合你的目的.引用的文档告诉你确切的事实.Cmd-如果您想自己阅读,请在Xcode中单击"UI_USER_INTERFACE_IDIOM()"以转到标题. (2认同)