-
实现两个view controller对象,一个做竖屏显示布局,另一个做横屏显示布局。按照本文前面所述方法设置每个view controller只支持特定的一种界面方向,以防止在设备旋转时,view controller内部自行做旋转操作。
-
主view controller(通常为竖屏的那个)注册
接收UIDeviceOrientationDidChangeNotification通知,在通知的处理方法中,根据当前的设备方向presen或dismiss另一个view controller。
参考代码如下:
@implementation PortraitViewController { BOOL isShowingLandscapeView; LandscapeViewController *landscapeViewController; } - (id)init { self = [super init]; if (self) { landscapeViewController = [[LandscapeViewController alloc]init]; [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil]; } return self; } -(void)orientationChanged:(NSNotification *)notification { UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation; if (UIDeviceOrientationIsLandscape(deviceOrientation) && !isShowingLandscapeView) { [self presentModalViewController:landscapeViewController animated:YES]; isShowingLandscapeView = YES; }else if(UIDeviceOrientationIsPortrait(deviceOrientation) && isShowingLandscapeView){ [self dismissModalViewControllerAnimated:YES]; isShowingLandscapeView = NO; } } -(NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; } -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation { if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) { return YES; } return NO; } ... @end @implementation LandscapeViewController - (id)init { self = [super init]; if (self) { self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; } return self; } -(NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskLandscape; } -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation { if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) { return YES; } return NO; } ... @end