ios8 强制横竖屏

项目需求是这样的:

项目整体是横屏,但是有一个页面需要竖屏。
这个时候,就是想要一个页面,这改动这一个页面的代码,就可以实现整个项目不因为这单独的页面横竖屏而改动。代码如下:
我们在进入这个页面的时候对用自定义的方法(方法就是横竖屏的方法),传入ture参数:

- (void)viewDidLoad {
    [super viewDidLoad];    
    [self hengshuping:true];
}
// 或者:
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hengshuping:true];
}

然后在页面消失的时候,传入false参数

- (void)viewWillDisappear:(BOOL)animated {
    [self hengshuping:false];
    [super viewWillDisappear:animated];
}

这样,我们就可以做到进入页面和页面消失后横竖屏不影响其他的页面了。下面是我们的自定义的横竖屏:

- (void)hengshuping:(BOOL)m_bScreen {

    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        NSNumber *num = [[NSNumber alloc] initWithInt:(m_bScreen?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait)];
        [[UIDevice currentDevice] performSelector:@selector(setOrientation:) withObject:(id)num];
        [UIViewController attemptRotationToDeviceOrientation];//这行代码是关键
    }

    SEL selector=NSSelectorFromString(@"setOrientation:");
    NSInvocation *invocation =[NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:[UIDevice currentDevice]];
    int val =m_bScreen?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait;
    [invocation setArgument:&val atIndex:2];
    [invocation invoke];
}

OK,完美解决项目的单个页面横竖屏问题。不过大家记在一个,就是项目的开始设置中,设置项目的Device Orientation的时候,要把四个方向都选上。不然上面的m_bScreen参数在判断的时候不能分辨当前的方向。
问题又来了,处女情结的程序员会发现,这个时候,所有的页面都支持横竖屏啊,只是这个特别的页面强制横屏了,其他的页面因为m_bScreen需要判断方向的原因而需要支持所有的方向。所以,下面的代码就可以解决除了需要强制横屏的页面外,其他的页面仅仅支持竖屏(项目可以横竖屏都支持的,就可以不用往下面看啦):

  1. 我们需要设置一个Category,下面是我的代码:
.h文件  
#import <UIKit/UIKit.h>

@interface UINavigationController (oritent)

@end

.m文件  
#import "UINavigationController+oritent.h"

@implementation UINavigationController (oritent)

- (BOOL)shouldAutorotate
{
    return self.topViewController.shouldAutorotate;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return self.topViewController.supportedInterfaceOrientations;
}

@end
  1. 设置这个Category后,项目里面都会受到影响的,这也是Category的使用本质。我们添加的两个方法,默认对项目没有任何影响的来,但是我们现在是想有影响,影响就是是的我们的页面,仅仅支持竖屏。好来,我们可以这样做,我们在我们想要仅仅支持竖屏的viewcontroller中,添加下面的代码:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(BOOL)shouldAutorotate
{
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

这样此页面就仅仅支持竖屏了。
OK,项目的横竖屏问题完美解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值