【问题标题】:Loading different xib for iPhone 5 fails为 iPhone 5 加载不同的 xib 失败
【发布时间】:2013-06-26 21:32:18
【问题描述】:

我正在尝试让我的应用检测用户是否在 iPhone 5 屏幕上。

我在其他视图中成功使用了以下方法。

我通过一个按钮调用 Xib / 视图来加载

- (IBAction)DemoTapeTwo:(id)sender {

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
    DemoTapeTwoViewController *Second = [[DemoTapeTwoViewController alloc] initWithNibName:nil bundle:nil];
    [self presentViewController:Second animated:YES completion:NULL];

} else {
    DemoTapeTwoViewController *Second = [[DemoTapeTwoViewController alloc] initWithNibName:@"DemoTapeTwoViewController_iPad" bundle:nil];
    [self presentViewController:Second animated:YES completion:NULL];


 }

我有两个xib,

iPhone 5 一:XViewController_568.xib

iPhone 4 一:XViewController.xib

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
if ([[ UIScreen mainScreen ] bounds ].size.height == 568 ) {
    nibName = [NSString stringWithFormat:@"%@_568", nibName];
}
if (self = [super initWithNibName:nibName bundle:nibBundle]) {

}
return self;
}

这个 ^ 在 .m 文件中

它应该会检测屏幕是 iPhone 5 还是 iPhone 4 屏幕并调整 Xib 到它。

但是,Xcode 出错了:

由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序, 原因:'无法在包中加载 NIB:'NSBundle /Users/SamGuichelaar/Library/Application Support/iPhone Simulator/6.1/Applications/321B4512-7BD3-46D8-A944-F12029448326/Parkway Drive Gestures.app(已加载)' '(空)_568'' 首先抛出调用栈:

所以,出了点问题,导致它找不到 iPhone 4 Xib 的原始名称。

谁能帮帮我?

【问题讨论】:

  • 从您的异常消息中可以清楚地看出,您的 initWithNibName:bundle: 方法正在使用 nil 参数调用 - 因此是“(null)_568”
  • 但它完美地适用于另一个项目。知道如何解决这个问题吗?
  • 我猜您是在另一个项目中手动调用该方法?怎么样,在哪里以及如何实例化这个视图控制器?
  • 在您的第一个 if 条件中,您似乎将 nil 作为笔尖名称传递。如果将其更改为 [[DemoTapeTwoViewController alloc] initWithNibName:@"DemoTapeTwoViewController" bundle:nil]; 会发生什么

标签: ios cocoa-touch


【解决方案1】:

我建议检查 nibName 是否为 nil,如果是,请使用类名。

我喜欢使用?: 进行这种快速替换。

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
    if ([[ UIScreen mainScreen ] bounds ].size.height == 568 ) {
        nibName = [NSString stringWithFormat:@"%@_568", nibName ?: @"DemoTapeTwoViewController"];
    }

    if (self = [super initWithNibName:nibName bundle:nibBundle]) {

    }
    return self;
}

要使其更通用,请使用NSStringFromClass()

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
    if ([[ UIScreen mainScreen ] bounds ].size.height == 568 ) {
        nibName = [NSString stringWithFormat:@"%@_568", nibName ?: NSStringFromClass([self class])];
    }

    if (self = [super initWithNibName:nibName bundle:nibBundle]) {

    }
    return self;
}

【讨论】:

  • 谢谢,这已经帮我解决了。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-06
  • 1970-01-01
相关资源
最近更新 更多