公司App里面有个需求,即所有界面都是竖屏,且不允许横屏切换,唯独有一个图表界面允许横屏。那么,根据此需求处理如下:
首先,确保App本身应该允许转屏切换:
再次,我的App里面都是走UINavigationController进行界面push切换的,所以首先创建一个UINavigationController的子类,并设定允许转屏:
1 @implementation AppExtendNavigationController 2 - (void)viewDidLoad { 3 [super viewDidLoad]; 4 // Do any additional setup after loading the view. 5 } 6 - (void)didReceiveMemoryWarning { 7 [super didReceiveMemoryWarning]; 8 // Dispose of any resources that can be recreated. 9 } 10 #pragma mark 转屏方法重写 11 -(UIInterfaceOrientationMask)supportedInterfaceOrientations 12 { 13 return [self.viewControllers.lastObject supportedInterfaceOrientations]; 14 } 15 -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation 16 { 17 return [self.viewControllers.lastObject preferredInterfaceOrientationForPresentation]; 18 } 19 -(BOOL)shouldAutorotate{ 20 return self.visibleViewController.shouldAutorotate; 21 }
最后,在你不想转屏切换的ViewController上重写以下方法:
1 #pragma mark 转屏方法 不允许转屏 2 -(UIInterfaceOrientationMask)supportedInterfaceOrientations 3 { 4 return UIInterfaceOrientationMaskPortrait ; 5 } 6 - (BOOL)shouldAutorotate 7 { 8 return NO; 9 } 10 -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation 11 { 12 return UIInterfaceOrientationPortrait; 13 } 14 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{ 15 return NO; 16 }
在你想转屏切换的ViewController上可以照这样重写(允许左右横屏以及竖屏):
1 - (BOOL)shouldAutorotate { 2 return YES; 3 } 4 -(UIInterfaceOrientationMask)supportedInterfaceOrientations 5 { 6 return UIInterfaceOrientationMaskAll; 7 } 8 - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation 9 { 10 return UIInterfaceOrientationPortrait; 11 } 12 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 13 { 14 return YES; 15 }
另外,在ViewController中对于转屏事件可以参见下面的方法进行捕获:
1 - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator 2 { 3 [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; 4 [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) { 5 //计算旋转之后的宽度并赋值 6 CGSize screen = [UIScreen mainScreen].bounds.size; 7 //界面处理逻辑 8 self.lineChartView.frame = CGRectMake(0, 30, screen.width, 200.0); 9 //动画播放完成之后 10 if(screen.width > screen.height){ 11 NSLog(@"横屏"); 12 }else{ 13 NSLog(@"竖屏"); 14 } 15 } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) { 16 NSLog(@"动画播放完之后处理"); 17 }]; 18 }
区分当前屏幕是否为横竖屏的状态,其实通过判断当前屏幕的宽高来决定是不是横屏或者竖屏:
竖屏时:宽<高
横屏时:宽>高
以上在IOS8、9中测试通过