iOS全局禁止横屏后,部分页面选择性横屏

712 阅读1分钟

iOS全局禁止横屏后,部分页面选择性横屏

平常开发中大部分App没有适配横屏的需求,但是在个别页面,有横屏的诉求。以播放视频为例,我们需要在播放视频时横屏,退出播放视频页面时禁止横屏。

AppDelegate.h 中添加属性,代表是否允许横屏

/*** 是否允许横屏的标记 */
@property (nonatomic,assign)BOOL allowRotation;

AppDelegate.m中增加代理方法,控制横竖屏的支持

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
  if (self.allowRotation) {
      return UIInterfaceOrientationMaskAllButUpsideDown;
  }
  return UIInterfaceOrientationMaskPortrait;
}

这样在其他页面想要横屏的时候,我们只要控制allowRotation即可

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = YES;//允许横屏
appDelegate.allowRotation = NO;// 不允许横屏
播放页面横屏实例

可以通过UIWindow的通知,来监听手机的横/竖屏方位

//监听UIWindow显示 开启全屏
  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(beginFullScreen) name:UIWindowDidBecomeVisibleNotification object:nil];
   
  //监听UIWindow隐藏 退出全屏
  [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];

在退出全屏时,需增加逻辑使上一个页面竖屏展示。

- (void)beginFullScreen
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  appDelegate.allowRotation = YES;
}
​
- (void)endFullScreen
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  appDelegate.allowRotation = NO;
   
  //强制归正:
      if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
          SEL selector = NSSelectorFromString(@"setOrientation:");
          NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
          [invocation setSelector:selector];
          [invocation setTarget:[UIDevice currentDevice]];
          int val =UIInterfaceOrientationPortrait;
          [invocation setArgument:&val atIndex:2];
          [invocation invoke];
      }
   
}


\