如今開發的APP大部分界面是豎屏的,只有視頻播放的界面和webview閱讀文字的界面是能夠橫屏操做的。web
那麼就進行以下處理:ide
一、首先確保APP支持橫屏旋轉測試
二、個人App裏面都是走UINavigationController進行界面push切換的,因此首先建立一個UINavigationController的子類,並設定容許轉屏: 動畫
#pragma mark 轉屏方法重寫 -(UIInterfaceOrientationMask)supportedInterfaceOrientations { return [self.viewControllers.lastObject supportedInterfaceOrientations]; } -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return [self.viewControllers.lastObject preferredInterfaceOrientationForPresentation]; } -(BOOL)shouldAutorotate{ return self.visibleViewController.shouldAutorotate; }
在不想轉屏切換的ViewController上重寫如下方法:spa
#pragma mark 轉屏方法 不容許轉屏 -(UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait ; } - (BOOL)shouldAutorotate { return NO; } -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return UIInterfaceOrientationPortrait; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{ return NO; }
在想轉屏切換的ViewController上能夠照這樣重寫(容許左右橫屏以及豎屏):code
- (BOOL)shouldAutorotate { return YES; } -(UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAll; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return UIInterfaceOrientationPortrait; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return YES; }
另外,在ViewController中對於轉屏事件能夠參見下面的方法進行捕獲:視頻
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) { //計算旋轉以後的寬度並賦值 CGSize screen = [UIScreen mainScreen].bounds.size; //界面處理邏輯 self.lineChartView.frame = CGRectMake(0, 30, screen.width, 200.0); //動畫播放完成以後 if(screen.width > screen.height){ NSLog(@"橫屏"); }else{ NSLog(@"豎屏"); } } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) { NSLog(@"動畫播放完以後處理"); }]; }
區分當前屏幕是否爲橫豎屏的狀態,其實經過判斷當前屏幕的寬高來決定是否是橫屏或者豎屏:blog
豎屏時:寬<高事件
橫屏時:寬>高webview
以上在IOS八、9中測試經過