iOS强制竖屏

以强制竖屏为例,强制横屏同理。

如果要全部竖屏,直接在Info.plist中设置即可。这里讨论的是全局可转屏,但是某些页面只能竖屏。

要做到强制竖屏,有两个要点。

1. 禁止转屏

2. 竖屏进入页面。

仅仅设置禁止转屏还不能保证一定是竖屏的。因为如果从横屏的状态进入当前页面的的话,当前页面就会也是横屏的。所以要强制竖屏,除了禁止转屏,还要做到竖屏进入页面。


禁止转屏

禁止转屏可以通过重写shouldAutoRotate实现。iOS7中,需要增加UINavigationController的支持。

具体参考iOS7中禁止某些页面转屏

实现扩展

#import "UINavigationController+Autorotate.h"

@implementation UINavigationController (Autorotate)

-(BOOL)shouldAutorotate {
    return [[self.viewControllers lastObject] shouldAutorotate];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation];
}

-(NSUInteger)supportedInterfaceOrientations{
    return [[self.viewControllers lastObject] supportedInterfaceOrientations];
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return [[self.viewControllers lastObject] shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
}
@end


竖屏进入页面

要做到竖屏进入页面,根据网上的资料,一个是调用setOrientation,一个是设置transform。

参考iOS Orientation,想怎么转怎么转

1. transform的方式我没有实现。

转屏没有问题,但是因为项目用的是AutoLayout,所以修改view的bounds的时候,不起作用。没有找到解决办法。

2. setOrientation一开始不起作用。因为设置了shouldAutoRotate为NO。所以横屏启动的时候,也没法转成竖屏。

修改下

-(BOOL)shouldAutorotate{
    return UIInterfaceOrientationIsLandscape(self.interfaceOrientation);
}

这样就是横屏可以转,竖屏不能转。

也就能保证横屏启动的时候,可以转成竖屏,但是转成竖屏之后,就不再能转成横屏。(强制横屏时,相反地,只允许竖屏转)

强制转屏的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    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];
    }
    
    //...
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值