I want to load different .xib
for iPhone 4 and 5.
I have three files FirstViewController.h
, FirstViewController.m
and FirstViewController.xib
I have added one more empty .xib
file for iPhone 5
and named it FirstViewController4Inch.xib
.
Here is my code snippet:
- (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;
}
When I run my app on both 3.5 and in 4 it gives the error:
Error:Could not load NIB in bundle:
I think this would work:
- (id)init
{
if ([[UIScreen mainScreen] bounds].size.height == 480)
{
self = [super initWithNibName:@"FirstViewController" bundle:nil];
}
else
{
self = [super initWithNibName:@"FirstViewController4Inch" bundle:nil];
}
return self;
}
as long as you create it programmatically using:
myVC = [[MyViewController alloc] init];
省略.xib部分。
self = [super initWithNibName:@"FirstViewController" bundle:nil];
Remove this line
self = [super initWithCoder:aDecoder];
Also make sure that both .xibs have your class as file owner.
Change your method like this :
- (id)init
{
self = (IS_IPHONE5() ? [super initWithNibName:@"FirstViewController4Inch" bundle:nil] : [super initWithNibName:@"FirstViewController" bundle:nil]);
if (self)
{
// Custom initialization
}
return self;
}
and use the macro IS_IPHONE5()
#define IS_IPHONE5() ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) && [UIScreen mainScreen].bounds.size.height == 568)
use this:
- (id)initForCustomScreen
{
NSString *nibName = ([[UIScreen mainScreen] bounds].size.height == 480 ? @"FirstViewController" : @"FirstViewController4Inch");
self = [super initWithNibName:nibName bundle:nil];
if (self) {
// initialisation code
}
return self;
}
The solution is a combination of Nickos and Maggie. Here is the merged solution which uses the View Controller Class name to provide the Nib name:
- (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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.