用于确定是在iPhone还是iPad上运行的API

Eri*_*ric 32 iphone cocoa-touch objective-c uidevice ipad

是否有用于在运行时检查您是在iPhone还是iPad上运行的API?

我能想到的一种方法是使用:

[[UIDevice currentDevice] model];
Run Code Online (Sandbox Code Playgroud)

并检测字符串@"iPad"的存在 - 这看起来有点脆弱.

在3.2 SDK中,我看到它UIDevice也有一个我正在寻找的属性,但不适用于3.2之前(显然):

[[UIDevice currentDevice] userInterfaceIdiom]; 
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以检查通用应用程序是否存在@"iPad"?

And*_*iih 41

结帐UI_USER_INTERFACE_IDIOM.

返回当前设备支持的接口惯用法.


UIUserInterfaceIdiomPhone如果设备是iPhone或iPod touch或UIUserInterfaceIdiomPad设备是iPad,则返回值.

UIUserInterfaceIdiom

应在当前设备上使用的接口类型

typedef enum {
   UIUserInterfaceIdiomPhone,
   UIUserInterfaceIdiomPad,
} UIUserInterfaceIdiom;
Run Code Online (Sandbox Code Playgroud)

  • 使用宏 - 以后的操作系统将响应选择器,但不一定是iPad. (7认同)
  • 需要注意的一点是:如果iPad用户正在运行仅限iPhone的应用程序(如非通用),则UI_USER_INTERFACE_IDIOM功能会将设备报告为iPhone. (5认同)

Dan*_*ark 15

仅供我参考:

@property (nonatomic, readonly) BOOL isPhone;

-(BOOL)isPhone {
    return (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone);
}
Run Code Online (Sandbox Code Playgroud)

或使用#define

#define IS_PHONE  (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用的是isPhone整个代码,那通常是不好的做法.使用工厂模式和多态来保持您的if语句包含,这样您就可以获得为手机或iPad创建的对象,然后使用它们.

添加

我现在在我的代码中使用这个解决方案.它在alloc中添加了标准工厂模式.

#define ALLOC_PER_DEVICE()  id retVal = nil; \
                        NSString *className = NSStringFromClass(self);\
                        if (IS_PHONE && ![className hasSuffix:@"Phone"]) {\
                            className = [NSString stringWithFormat:@"%@Phone", className];\
                            Class newClass = NSClassFromString(className);\
                            retVal = [newClass alloc];\
                        }\
                        if (!retVal)\
                            retVal = [super alloc];\
                        assert(retVal != nil);\
                        return retVal\
Run Code Online (Sandbox Code Playgroud)

然后我的allocs看起来像这样:

+alloc { ALLOC_PER_DEVICE(); }
Run Code Online (Sandbox Code Playgroud)

我添加了一个名为TheClassPhone手机版的子类.

注意:由于Objective-C中没有多重继承,因此使用继承来解决您的问题有点过高(即,如果您有子类的子类,它就不起作用).if当你需要时,没有什么比这更好了.