iOS 强制横屏的方法

开发背景是项目当中有一个单独的页面是需要进入到那个页面的时候是支持横屏的,旋转屏幕或者手动切换都支持横屏,但是其他的页面均是竖屏,下面就是具体的操作和代码:

首先在AppDelegate.h里面设置一个控制横屏的属性

   //是否横屏
   @property (nonatomic,assign)NSInteger allowRotate;

然后在.m的里面设置方法

//此方法会在设备横竖屏变化的时候系统会调用
  - (UIInterfaceOrientationMask)application:(UIApplication *)application       supportedInterfaceOrientationsForWindow:(UIWindow *)window
  {

      //   NSLog(@"方向  =============   %ld", _allowRotate);
      if (_allowRotate == 1) {
          return UIInterfaceOrientationMaskAll;
      }else{
        return (UIInterfaceOrientationMaskPortrait);
      }

  }

// 返回是否支持设备自动旋转
  - (BOOL)shouldAutorotate
  {
      if (_allowRotate == 1) {
          return YES;
      }
      return NO;
  }

以上就是关于delegate的设置,之后进入到你需要横屏的视图控制器的.m文件,首先导入delegate.h,然后在下面相应的方法里面加上如下代码:

-(void)viewWillAppear:(BOOL)animated{//页面加载时,允许他可以横屏
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowRotate = 1;

}

-(void)viewWillDisappear:(BOOL)animated{//页面退出时让下一个页面竖屏
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowRotate = 0;

    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];
    }
}

如果想实现点击某个button时候实现手动横屏的话,可以在button的点击事件里面加上如下代码

 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 = UIInterfaceOrientationLandscapeRight; //UIInterfaceOrientationPortrait 这个是竖屏
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }

最后如果在横屏了页面的同时需要改变UI或者自适应UI的话需要在该页面的viewdidload写一个监听屏幕变化的方法,可以如下:

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(你需要执行改变UI的方法) name:UIDeviceOrientationDidChangeNotification object:nil];

这个方式打开该页面的时候不是自动横屏的,如果要求是打开该页面时自动横屏的话可以在viewWillAppear:加一个段横屏的代码

你可能感兴趣的:(iOS)