iOS 实现单个页面支持横竖屏,其他页面只能竖屏

 最近在自己的项目里面  有需要做一个需求 : app中某一个页面支持横竖屏, 而其他页面只能竖屏。 
  • 1
  • 2

实现方法如下: 
1 首先需要Xcode中选中支持的屏幕方向 
这里写图片描述

2 Appdelegate中 
.h

@property (nonatomic,assign)NSInteger allowRotate; 
  • 1

.m中

//此方法会在设备横竖屏变化的时候调用
- (NSUInteger)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; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

3 在需要支持横竖屏的controller中:

viewWillApplear 中

 //在视图出现的时候,将allowRotate改为1,
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowRotate = 1;
  • 1
  • 2
  • 3

viewWillDisappear中

 //在视图出现的时候,将allowRotate改为0,
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowRotate = 0;
  • 1
  • 2
  • 3

写好以上代码之后, 会发现一些问题: 当横屏页面直接点击“返回”按钮退出的时候, 页面依然是横屏, 而我们需要的是仅一个页面可以横屏,测试需要在viewWillDisappear中加入如下代码:

    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];
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

此时就可以使app仅有设置页面支持横竖屏了!

此时如果app要求用户在横屏 竖屏的模式下改变UI(横屏与竖屏对应不同的UI), 可以在以下方法中执行

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    // do something before rotation
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) { 屏幕从竖屏变为横屏时执行 }else{ 屏幕从横屏变为竖屏时执行 } } - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { // do something after rotation }

转载于:https://www.cnblogs.com/sunfuyou/p/8533656.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值