iOS橫豎屏

黑暗森林的歌者發表於2018-02-26

首先,確保APP支援螢幕旋轉,具體怎麼支援,去網上查詢一下

然後,在對應的類中進行如下操作

#pragma mark 轉屏方法重寫
-(UIInterfaceOrientationMask)supportedInterfaceOrientations {    
    return [self.viewControllers.lastObject supportedInterfaceOrientations];
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {    
  return [self.viewControllers.lastObject preferredInterfaceOrientationForPresentation];
}
-(BOOL)shouldAutorotate { 
     return self.visibleViewController.shouldAutorotate;
}
複製程式碼

最後,在你不想轉屏切換的ViewController上重寫以下方法:

#pragma mark 轉屏方法 不允許轉屏
-(UIInterfaceOrientationMask)supportedInterfaceOrientations {  
      return UIInterfaceOrientationMaskPortrait ;
}
- (BOOL)shouldAutorotate{    
  return NO;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return NO;
}
複製程式碼

在你想轉屏切換的ViewController上可以照這樣重寫(允許左右橫屏以及豎屏):

- (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(@"動畫播放完之後處理");    
    }];
}
複製程式碼

區分當前螢幕是否為橫豎屏的狀態,其實通過判斷當前螢幕的寬高來決定是不是橫屏或者豎屏:

**豎屏時:**寬<高

**橫屏時:**寬>高

相關文章