iOS 单页面切换横屏问题

第一步

在AppDelegate中添加方法关闭横竖屏切换,方法如下

AppDelegate.h中外露一个属性

@property( nonatomic , assign ) BOOL allowRotation;//标识是否允许转向

AppDelegate.m中增加如下方法

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{
    if (_allowRotation == YES) {   // 如果属性值为YES,仅允许屏幕向左旋转,否则仅允许竖屏
        return UIInterfaceOrientationMaskLandscapeRight;  // 此处是屏幕要旋转的方向
    }else{
        return (UIInterfaceOrientationMaskPortrait);
    }
}

第二步

在需要强制横屏的页面写上如下代码:

  • 在viewDidLoad 方法设置如下:
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = YES;//(打开AppDelegate里的横屏开关)
[self setNewOrientation:YES];//调用转屏代码
  • 实现setNewOrientation方法:
- (void)setNewOrientation:(BOOL)fullscreen{
    if (fullscreen) {
        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    }else{
        NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
        [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    }
}

注意点

有些导航控制器push出来的页面,如果在导航控制器里写了侧滑代理及手势,可能会导致部分强制横屏页面没法横屏,此时需要把导航控制器里侧滑手势代码屏蔽删除即可。

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //就这句话导致了push出来的页面无法强制横屏
    //self.interactivePopGestureRecognizer.delegate = self;
    
    self.navigationBar.barTintColor = [UIColor whiteColor];//64B4FA//64C83C//7F9CFF
    [self.navigationBar setTitleTextAttributes:@{NSFontAttributeName:T18Font_M, NSForegroundColorAttributeName:C16}];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,617评论 0 11
  • 彩排完,天已黑
    刘凯书法阅读 4,305评论 1 3
  • 表情是什么,我认为表情就是表现出来的情绪。表情可以传达很多信息。高兴了当然就笑了,难过就哭了。两者是相互影响密不可...
    Persistenc_6aea阅读 126,159评论 2 7