如何在通用应用程序中区分iPhone和iPad?

问题描述:

我想区分iPhone和iPad的控制器。如何在通用应用程序中区分iPhone和iPad?

 #ifdef __IPHONE_NA 
      { 

      UINavigationBar *ipadNavBar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 768.0f, 50.0f)]; 
      [[self view] addSubview: ipadNavBar]; 

      UINavigationItem *ipadNavItem = [[UINavigationItem alloc] initWithTitle: @"EMPLOYEE"]; 
      [ipadNavBar pushNavigationItem:ipadNavItem animated:NO]; 
      } 
    else 
     { 

     UINavigationBar *ipadNavBar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 360.0f, 45.0f)]; 
     [[self view] addSubview: ipadNavBar]; 



UINavigationItem *ipadNavItem = [[UINavigationItem alloc] initWithTitle: @"EMPLOYEE"]; 
    [ipadNavBar pushNavigationItem:ipadNavItem animated:NO]; 
    } 

如果说错误未终止的#ifdef

是这种做法是否正确?

您可以使用常量已经存在的:

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) 
{ 
    // Some code for iPhone 
} 
else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
{ 
    // Some code for iPad 
} 

当然,你不会需要else if声明,你可以只使用else但我只是用它说明了差异常数可用。

你可以找到更多here(看看UI_USER_INTERFACE_IDIOM部分)。

+0

thanks Crazy Chimp! – user905582 2012-01-07 23:54:02

+0

没问题 - 很高兴我能帮上忙! – 2012-01-08 11:21:38

+0

应用程序需要通用才能执行iPad程序块。 – 2014-11-14 00:08:10

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
     NSLog(@"iPad Idiom"); 
    else 
     NSLog(@"iPhone Idiom"); 

if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { 

    Console.WriteLine("Phone"); 

} else if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { 

    Console.WriteLine("Pad"); 

} 
+3

良好的答案伴随代码示例以及未来读者的解释。当问这个问题的人可能会理解你的答案时,解释你如何到达它会帮助无数其他人。 – 2014-08-04 12:51:59