【问题标题】:How can i load the different xibs for single class depends on current device in iOS?如何根据 iOS 中的当前设备为单个类加载不同的 xib?
【发布时间】:2012-12-31 16:14:37
【问题描述】:

我在视图控制器中有完整的代码。所以,我需要在 iPad、iPhone 和 iPod 中显示相同的输出。那么,我正在使用单视图控制器来处理数据。为此,我如何选择可能 ipod 或 ipad 取决于 iOS 中当前设备的不同 XIB?

我想要一个视图控制器和 2 个 XIB,而不是再创建一个视图控制器

【问题讨论】:

  • if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { ViewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];但我只需要加载 xib ..我怎么能? } else { viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil] autorelease]; }
  • 将 ~ipad 后缀添加到 xib 名称。例如:MyViewController~ipad.xib。 [[MyViewController alloc] initWithNibName:"MyViewController" ...]

标签: iphone ios ipad uiviewcontroller xib


【解决方案1】:

[UIDevice currentDevice] 将为您提供有关当前设备的详细信息。在 if 循环中使用它并为 iphone 或 i pad 选择 xib。

    if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) 
{
 load 1 xib 
} 
else 
{ 
load another 
}

【讨论】:

  • 不需要这样做,iOS 可以通过使用名称中的平台说明符如~ipad~iphone 来为您完成。
【解决方案2】:

当你创建一个通用应用程序时,这非常简单,它本身会让代码检查设备类型并加载特定的 xib。

例如

 if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil] autorelease];
    } else {
        self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil] autorelease];
    }

【讨论】:

  • 不需要这样做,iOS 可以通过使用名称中的平台说明符,如~ipad~iphone 来为您完成。
【解决方案3】:
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil] autorelease];
}
else
{
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil] autorelease];
}

【讨论】:

  • 如果你当前的设备是iphone/ipod,用一个.xib初始化控制器,否则用另一个.xib初始化
  • 但是我没有 iPad 的 .h 和 .m 文件。我只有 viewController_ipad.xib。当我使用你的代码时,我得到没有数据的空视图。
  • 您有两个不同的 .xib 文件,对吗?在这种情况下,打开 .xib,单击文件的所有者对象,然后在“身份检查器”中将其类设置为“视图控制器”类。最后连接所有插座,对两个 .xibs 重复此过程
  • 不需要这样做,iOS 可以通过使用名称中的平台说明符,如~ipad~iphone 来为您完成。
  • 如果你从 appdelegate 初始化你的 viewcontroller,那么你可以在 appdelegate 中检查它,或者你甚至可以重载你的 viewcontroller 来执行这个检查,即重载 [initWithNibName: bundle:]
猜你喜欢
  • 2012-12-31
  • 2013-05-14
  • 2014-03-30
  • 2011-02-10
  • 1970-01-01
  • 2014-02-13
  • 2011-11-01
  • 1970-01-01
  • 2011-11-07
相关资源
最近更新 更多