使用一个UIViewController和两个XIB在iPad上处理方向更改

Sim*_*lli 9 landscape rotation nib ipad

我想处理与一个UIViewController中和两个XIBs的iPad应用方向的变化,让我们说MenuView和MenuViewLandscape.

所以,在MenuViewController的willRotateToInterfaceOrientation方法,我怎么能更改,恕不使用其他控制器为风景模式XIB?

我正在使用以下代码:

if( toInterfaceOrientation != UIInterfaceOrientationPortrait ){
    MenuViewController *landscape = [[MenuViewController alloc] 
                                        initWithNibName: @"MenuViewLandscape"
                                        bundle:nil 
                                    ];        
    [self setView:landscape.view];
}
else {
    MenuViewController *potrait = [[MenuViewController alloc] 
                                     initWithNibName: @"MenuView"
                                     bundle:nil 
                                  ];        
    [self setView:potrait.view];
}
Run Code Online (Sandbox Code Playgroud)

但是当我去横向查看XIB时,横向视图控件没有正确旋转.

jus*_*ger 12

我不确定这个实现有什么奇怪的副作用,但尝试这样的事情,看看它是否适合你:

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration {
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        [[NSBundle mainBundle] loadNibNamed:@"MenuView" owner:self options:nil];
        if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            self.view.transform = CGAffineTransformMakeRotation(M_PI);
        }
    } else if (UIInterfaceOrientationIsLandscape(orientation)){
        [[NSBundle mainBundle] loadNibNamed:@"MenuViewLandscape" owner:self options:nil];
        if (orientation == UIInterfaceOrientationLandscapeLeft) {
            self.view.transform = CGAffineTransformMakeRotation(M_PI + M_PI_2);
        } else {
            self.view.transform = CGAffineTransformMakeRotation(M_PI_2);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这假设您的MenuView和MenuViewLandscape XIB中的文件所有者都设置为MenuViewController,并且视图出口也设置在两个XIB中.使用时,所有插座都应在旋转时正确重新连接loadNibNamed.

如果您正在为iOS 4构建,您还可以loadNibNamed使用以下代码替换这些行:

UINib *nib = [UINib nibWithNibName:@"MenuView" bundle:nil];
UIView *portraitView = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
self.view = portraitView;
Run Code Online (Sandbox Code Playgroud)

UINib *nib = [UINib nibWithNibName:@"MenuViewLandscape" bundle:nil];
UIView *landscapeView = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
self.view = landscapeView;
Run Code Online (Sandbox Code Playgroud)

这些假定您要立即显示的UIView遵循XIB中的文件所有者和第一响应者代理对象.

然后,您只需确保视图旋转正确以适应界面方向.对于不在默认纵向方向上的所有视图,通过设置transform视图的属性并使用CGAffineTransformMakeRotation()适当的值来旋转它们,如上例所示.

单独轮换可以解决您的问题,而无需额外加载NIB.但是,加载a的全新实例MenuViewController并将其视图设置为现有MenuViewController视图可能会导致生命周期和旋转事件出现一些奇怪的行为,因此尝试上述示例可能会更安全.MenuViewController当您只需要从中获取视图时,它们还可以省去创建新实例的麻烦.

希望这可以帮助!

贾斯汀