iOS 横竖屏及状态栏的处理

开发中有竖屏和横屏的界面时,我们需要监听屏幕旋转,强制横屏,锁定方向后的屏幕强制旋转等处理.以下做个总结:

一.横竖屏配置

全局支持的方向需要做如下配置
方式1:

配置

方式2:
如果工程配置只支持竖屏

竖屏


我们可以直接用代码控制方向:

/// 在这里控制旋转方向
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.allowOrentitaionRotation) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    }
    return UIInterfaceOrientationMaskPortrait;
}

然后可以在 AppDelegate 通过一个参数控制支持的方向,最终都会以AppDelegate 中支持的方向为准。具体控制可参考代码。

plist文件:

View controller-based status bar appearance 设置为YES
这样就可以在每个控制器控制自己对应的方向状态栏样式等
注意这样的话
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
这种就不再起作用,另外这两个方法在iOS9后也不建议使用了

启动页不需要显示状态栏可以在plist如下设置

Status bar is initially hidden YES

另外每个页面需要如下配置,因此我们可以在BaseViewController配置

//是否可以旋转
- (BOOL)shouldAutorotate {
    return YES;
}
// 支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
//由模态推出的视图控制器 优先支持的屏幕方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationPortrait;
}
//是否隐藏状态栏
- (BOOL)prefersStatusBarHidden {
    return NO;
}
//状态栏样式
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

如果是有Navigation控制的,也需要在BaseNavigation里设置

// 是否可以旋转
- (BOOL)shouldAutorotate {
    return self.topViewController.shouldAutorotate;
}
// 支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return self.topViewController.supportedInterfaceOrientations;
}
// 由模态推出的视图控制器 优先支持的屏幕方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return self.topViewController.preferredInterfaceOrientationForPresentation;
}
// 是否隐藏状态栏
- (BOOL)prefersStatusBarHidden {
    return self.topViewController.prefersStatusBarHidden;
}
// 状态栏样式--以下两个都可以
- (UIStatusBarStyle)preferredStatusBarStyle {
    return self.topViewController.preferredStatusBarStyle;
}
//- (UIViewController *)childViewControllerForStatusBarStyle {
//    return self.topViewController;
//}

如果是有TabBarController控制的,也需要在BaseTabBarController里设置

//是否可以旋转
- (BOOL)shouldAutorotate {
    return self.selectedViewController.shouldAutorotate;
}
// 支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return self.selectedViewController.supportedInterfaceOrientations;
}
//由模态推出的视图控制器 优先支持的屏幕方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return self.selectedViewController.preferredInterfaceOrientationForPresentation;
}
//隐藏状态栏
- (BOOL)prefersStatusBarHidden {
    return self.selectedViewController.prefersStatusBarHidden;
}
//状态栏样式
- (UIStatusBarStyle)preferredStatusBarStyle {
    return self.selectedViewController.preferredStatusBarStyle;
}

这样的基础配置后,如果某个页面需要支持所有方向就可以重写对应的方法.
然后了解一下UIInterfaceOrientation:界面可支持的方向

typedef NS_OPTIONS(NSUInteger, UIInterfaceOrientationMask) {
    //界面支持横屏
    UIInterfaceOrientationMaskPortrait = (1 << UIInterfaceOrientationPortrait),
    //界面支持朝左   
    UIInterfaceOrientationMaskLandscapeLeft = (1 << UIInterfaceOrientationLandscapeLeft),
    //界面支持朝右 
    UIInterfaceOrientationMaskLandscapeRight = (1 << UIInterfaceOrientationLandscapeRight),
    //界面支持颠倒 
    UIInterfaceOrientationMaskPortraitUpsideDown = (1 << UIInterfaceOrientationPortraitUpsideDown),
    //界面支持左右
    UIInterfaceOrientationMaskLandscape = (UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight),
    //界面支持所有方向
    UIInterfaceOrientationMaskAll = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortraitUpsideDown),
    //界面支持除了颠倒的方向
    UIInterfaceOrientationMaskAllButUpsideDown = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight),
} __TVOS_PROHIBITED;

二.屏幕旋转监听以及相关处理

做好配置后我们就可以对各个方向进行配置,因此需要监听屏幕的各个方向,我们可以用UIApplicationDidChangeStatusBarOrientationNotification来监听,代码如下

//监听UIApplicationDidChangeStatusBarOrientationNotification
    //手机锁定竖屏此通知方法也失效了
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(statusBarOrientationChange:)
                                name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];

然后通过通知回调获取对应的方向

//界面方向改变的处理
- (void)statusBarOrientationChange:(NSNotification *)notification {
    
    UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    switch (interfaceOrientation) {
            
        case UIInterfaceOrientationUnknown:
            NSLog(@"未知方向");
            break;
            
        case UIInterfaceOrientationPortrait:
            NSLog(@"界面直立");
            break;
            
        case UIInterfaceOrientationPortraitUpsideDown:
            NSLog(@"界面直立,上下颠倒");
            break;
            
        case UIInterfaceOrientationLandscapeLeft:
            NSLog(@"界面朝左");
            break;
            
        case UIInterfaceOrientationLandscapeRight:
            NSLog(@"界面朝右");
            break;
        
        default:
            break;
    }
}

注意需要在dealloc移除监听
但是如果用户锁定屏幕方向后上面的方法时无法监听的
因此我们可以采用加速器来获取屏幕的方向
这里会用到 <CoreMotion/CoreMotion.h>
初始化

//sensitive 灵敏度
//目的是可以与系统的监听方法保持大概一致
static const float sensitive = 0.50;
- (CMMotionManager *)manager {
    if (!_manager) {
        _manager = [[CMMotionManager alloc] init];
        //更新的频率
        _manager.deviceMotionUpdateInterval = 0.3;
    }
    return _manager;
}

然后开始进行监听:

if (self.manager.deviceMotionAvailable) {
        NSLog(@"Device Motion Available");
        [self.manager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
                                      withHandler: ^(CMDeviceMotion *motion, NSError *error){
                                          [self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];
                                          
                                      }];
    } else {
        NSLog(@"No device motion on device.");
    }

监听后获取回调

- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion {
    UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    double x = deviceMotion.gravity.x;
    double y = deviceMotion.gravity.y;
    if (fabs(y) >= fabs(x)) {
        if (y >= 0) {
            // UIDeviceOrientationPortraitUpsideDown;
            NSLog(@"界面直立,上下颠倒");
        } else {
            // UIDeviceOrientationPortrait;
            NSLog(@"界面直立");
        }
    } else {
        if (x > sensitive) {
            // UIDeviceOrientationLandscapeRight;
            NSLog(@"界面朝右");
        } else if (fabs(x) > sensitive) {
            // UIDeviceOrientationLandscapeLeft;
            NSLog(@"界面朝左");
        } else {
            NSLog(@"界面直立");
        }
    }
}

注意我们需要在viewDidDisappear停止监听

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.manager stopDeviceMotionUpdates];
}

这样我们就可以做强制横屏的竖屏的操作了
强制横屏代码:

//强制转屏
- (void)setInterfaceOrientation:(UIInterfaceOrientation)orientation {
    
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector  = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        // 从2开始是因为前两个参数已经被selector和target占用
        [invocation setArgument:&orientation atIndex:2];
        [invocation invoke];
    }
}

三.状态栏的处理

如果我们要对状态栏进行处理需要对

- (BOOL)prefersStatusBarHidden;

做处理.然后参考一下官方文档

文档介绍

然后就可以写一个全局参数来控制状态栏的显示和隐藏
然后调用以下方法

[self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];

但是这样会导致导航栏上移
因此我们也可以采用如下方法进行控制

// 只在 iOS 13 以下有作用
UIView  *statusBar = [[UIApplication sharedApplication] valueForKey:@"statusBar"];
statusBar.hidden= YES;

或者

// 只在 iOS 13 以下有作用
UIView  *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
statusBar.hidden= YES;

iOS 13 以上只能设置背景,横屏后会自动消失

UIView *statusBar = [[UIView alloc] initWithFrame: [UIApplication sharedApplication].keyWindow.windowScene.statusBarManager.statusBarFrame] ;
statusBar.backgroundColor = [UIColor grayColor];
[[UIApplication sharedApplication].keyWindow addSubview:statusBar];

以上就是对应横竖屏处理的总结

使用过程遇到的问题
1.刘海屏在横屏后状态栏消失

iPhone XS Max

解决方法:

// 只在 iOS 13 以下有作用
UIView  *statusBar = [[UIApplication sharedApplication] valueForKey:@"statusBar"];
statusBar.hidden= NO;

虽然这样显示出状态栏,但是覆盖到了导航栏上了.因此还是自定义状态栏好一些.
iOS 13 以上会状态栏自动消失,还是自定义好一点。

四.利用动画旋转强制横屏

如果项目设置里面的屏幕控制只勾选 Portrait,我们可以利用动画旋转强制横屏

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 旋转角度 0.5➡️横屏 1.5⬅️横屏 2⬆️竖屏 1⬇️竖屏
    CGFloat duration = [UIApplication sharedApplication].statusBarOrientationAnimationDuration;//时间
    [UIView animateWithDuration:duration animations:^{
        self.navigationController.view.transform = CGAffineTransformMakeRotation(M_PI*0.5);
        self.navigationController.view.bounds = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.height, [[UIScreen mainScreen] bounds].size.width);
    }];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //视图将要消失的时候 再把视图翻转回来 ,不会影响其他VC的展示
    CGFloat duration = [UIApplication sharedApplication].statusBarOrientationAnimationDuration;
    [UIView animateWithDuration:duration animations:^{
        self.navigationController.view.transform = CGAffineTransformMakeRotation(M_PI*2);
        self.navigationController.view.bounds = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
    }];  
}

此方法效果一般,可进行优化。


链接:https://www.jianshu.com/p/f91482afe3a9
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值