7

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

+ (BOOL) isiPad
{
#ifdef UI_USER_INTERFACE_IDIOM
    return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
#endif
    return NO;
}

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)
4

1 回答 1

13

8.2 UserInterfaceIdiom()

#define UI_USER_INTERFACE_IDIOM() ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? [[UIDevice currentDevice] userInterfaceIdiom] : UIUserInterfaceIdiomPhone)

8.3 UserInterfaceIdiom()

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

所以#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;
}
于 2015-04-13T15:29:23.707 回答