0

我正在尝试让我的应用检测用户是否在 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 (loaded)' 名称为 '(null)_568'' 第一次抛出调用堆栈:

因此,出现了问题,导致它找不到 iPhone 4 Xib 的原始名称。

谁能帮我?

4

1 回答 1

3

我建议检查 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;
}
于 2013-06-26T22:03:47.660 回答