控制单个视图控制器旋转

本文介绍如何在iOS应用中使用代码控制屏幕旋转方向,包括在General->Deploymentinfo设置限制及通过重写UIViewController方法实现更精细的控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接控制App屏幕旋转方向:


我们可以直接在General -> Deployment info 里面设置限制app旋转方向,这样子就可以控制允许屏幕旋转哪几种方向了,但这个设置并不能实现所有项目的需求,比如做一下视频相关的app,其他的视图都是不允许横屏的,只有视频那个控制器能够横屏,这个时候你根本可能就没有办法再更改设置里面的内容了,只能通过代码去实现横屏。

代码实现控制屏幕旋转

iOS6.0 以后就是通过以下三个方法实现横竖屏的控制,在ViewController里面重写三个方法或创建一个该类的类目实现下面三个方法就能实现了:

-(BOOL)shouldAutorotate{
    return NO;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationPortrait;
}
复制代码

但是

如果你发现你的ViewController里面的 shouldAutorotate 然而并没有执行的时候,不用疑惑它为什么不执行,仔细想一下,它是UIViewController里面的方法,它不执行说明了什么情况呢?没错,就是被别的UIViewController截取了,而方法被截取说明了你这个视图控制器不是单一的UIViewController,它很有可能是被别的继承于UIViewController的类控制了或者说作为了子视图控制器,这个时候你可以检查一下,你的ViewController是不是作为了UINavigationControllerRootViewController或者被作为了UITabBarController的子控制器,如果是这样的话,只需要在你项目里面的UINavigationControllerUITabBarController添加同样的三个方法就行了

UINavigationController基类添加方法:

-(BOOL)shouldAutorotate{
    return self.topViewController.shouldAutorotate;
}
/**以下两个方法可不写*/
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    returnUIInterfaceOrientationLandscapeRight;
}
复制代码

UITabBarController基类添加方法:

- (BOOL)shouldAutorotate{
    return self.selectedViewController.shouldAutorotate;
}
/**以下两个方法可不写*/
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;
}
复制代码

转载于:https://juejin.im/post/5a34eb736fb9a04500031fff

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值