[iOS SDK] LandscapeとPortraitで xib ファイルを切り替える方法

自分はたいていコードで位置指定するのでこれまで遭遇していなかったけれども Landscape と Portrait で xib ファイル自体を切り替えて対応する方法を調べたのでメモしてみる。

Landscape と Portrait で部品の配置などが大きく異なり、コードでの指定や AutoLayoutでの指定が面倒なときにこの方法を使うことになると思われる。

そもそも今はこういうxibを指定する書き方はしないという話もありそうだけれども。いまだに昔からの書き方でやっている。

iphone – Easiest way to support multiple orientations? How do I load a custom NIB when the application is in Landscape? – Stack Overflow

にある、下記のコードで対応できた。

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if( !nibNameOrNil )    {
		 nibNameOrNil = [self nibNameRotated:[[UIApplication sharedApplication] statusBarOrientation]];
	}
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (NSString*) nibNameRotated:(UIInterfaceOrientation)orientation
{
    if( UIInterfaceOrientationIsLandscape(orientation))  {   
		return [NSString stringWithFormat:@"%@-landscape", NSStringFromClass([self class])];
	} else {
	    return [NSString stringWithFormat:@"%@", NSStringFromClass([self class])];
	}
}

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    NSString *nibname = [self nibNameRotated:toInterfaceOrientation];
    [[NSBundle mainBundle] loadNibNamed:nibname owner:self options:nil];
    [self viewDidLoad];
}

呼び出し側は

    xxxViewController *viewC = [[xxxViewController alloc]initWithNibName:nil bundle:nil];

のように、引数 nil で呼び出すことを想定している。
また、Landscape 用の xib ファイルは xxxViewController-landscape.xib とする。

基本的にはAdam氏の方法で対応できるのだが、最初からLandscape状態で呼び出されたときにwillRotateToInterfaceOrientation: が呼ばるまで Portrait状態になってしまうのでinitWithNibName: の対応が必要となりました。

返信を残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

This site uses Akismet to reduce spam. Learn how your comment data is processed.