我想为iPhone 4和5加载不同的.xib
。
我有三个文件FirstViewController.h
,FirstViewController.m
和FirstViewController.xib
我为.xib
添加了一个空的iPhone 5
文件,并将其命名为FirstViewController4Inch.xib
。
这是我的代码段:
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
if ([[UIScreen mainScreen] bounds].size.height == 480)
{
self = [super initWithNibName:@"FirstViewController.xib" bundle:nil];
}
else
{
self = [super initWithNibName:@"FirstViewController4Inch.xib" bundle:nil];
}
return self;
}
return self;
}
当我在3.5和4中运行我的应用程序时,它会出错:
Error:Could not load NIB in bundle:
答案 0 :(得分:1)
我认为这样可行:
- (id)init
{
if ([[UIScreen mainScreen] bounds].size.height == 480)
{
self = [super initWithNibName:@"FirstViewController" bundle:nil];
}
else
{
self = [super initWithNibName:@"FirstViewController4Inch" bundle:nil];
}
return self;
}
只要您使用以下命令以编程方式创建它:
myVC = [[MyViewController alloc] init];
答案 1 :(得分:1)
忽略.xib部分。
self = [super initWithNibName:@"FirstViewController" bundle:nil];
答案 2 :(得分:1)
删除此行
self = [super initWithCoder:aDecoder];
还要确保两个.xib都将您的类作为文件所有者。
答案 3 :(得分:0)
像这样改变你的方法:
- (id)init
{
self = (IS_IPHONE5() ? [super initWithNibName:@"FirstViewController4Inch" bundle:nil] : [super initWithNibName:@"FirstViewController" bundle:nil]);
if (self)
{
// Custom initialization
}
return self;
}
并使用宏IS_IPHONE5()
#define IS_IPHONE5() ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) && [UIScreen mainScreen].bounds.size.height == 568)
答案 4 :(得分:0)
使用它:
- (id)initForCustomScreen
{
NSString *nibName = ([[UIScreen mainScreen] bounds].size.height == 480 ? @"FirstViewController" : @"FirstViewController4Inch");
self = [super initWithNibName:nibName bundle:nil];
if (self) {
// initialisation code
}
return self;
}
答案 5 :(得分:0)
解决方案是Nickos和Maggie的组合。以下是使用View Controller Class名称提供Nib名称的合并解决方案:
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self)
{
NSString* nibName = NSStringFromClass([self class]);
if ([[UIScreen mainScreen] bounds].size.height == 480)
{
self = [super initWithNibName:nibName bundle:nil];
}
else
{
self = [super initWithNibName:[nibName stringByAppendingString:@"4inch"] bundle:nil];
}
return self;
}
return self;
}