iOS16 横竖屏切换适配

项目中针对某一个 View 需要进行横屏,在 iOS16 之前的方式大部分都是采取设置设备的方向来实现的,但是在 iOS16 开始这种方式已经无效了,如果使用设置设备方向来实现横竖屏切换,在 Xcode 的控制台中会输出以下信息:

[Orientation] BUG IN CLIENT OF UIKIT: Setting UIDevice.orientation is not supported. Please use UIWindowScene.requestGeometryUpdate(_:)

所以在 iOS16 开始如果要实现横竖屏切换,需要使用 UIWindowScene 的方式进行

iOS16 之前实现横竖屏切换方式

AppDelegate

AppDelegate 的 .h 文件中添加一个变量来记录是否需要进行横竖屏切换

@property (nonatomic, assign, getter=isLaunchScreen) BOOL launchScreen;    /**< 是否是横屏 */

AppDelegate 的 .m 文件中重写 launchScreensetter 方法

- (void)setLaunchScreen:(BOOL)launchScreen {

    _launchScreen = launchScreen;
    [self application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:nil];
}

并且实现 UIApplicationDelegateapplication:supportedInterfaceOrientationsForWindow: 方法

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {

    if (self.isLaunchScreen) {
        // 只支持横屏,并且 Home 按键在右边
        return UIInterfaceOrientationMaskLandscapeRight;
    }

    // 只支持竖屏
    return UIInterfaceOrientationMaskPortrait;
}

在需要实现横竖屏切换的 View

接下来在需要切换横竖屏的 View 中增加以下方法,就能在 iOS16 之前实现该功能

/// 切换设备方向
/// - Parameter isLaunchScreen: 是否是全屏
- (void)p_switchOrientationWithLaunchScreen:(BOOL)isLaunchScreen {

    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (isLaunchScreen) {
        // 全屏操作
        appdelegate.launchScreen = YES;
    } else {
        // 退出全屏操作
        appdelegate.launchScreen = NO;
    }
    // 设置设备的方向
    [self p_swichToNewOrientation:isLaunchScreen ? UIInterfaceOrientationLandscapeRight : UIInterfaceOrientationPortrait];
}
/// iOS16 之前进行横竖屏切换方式
/// - Parameter interfaceOrientation: 需要切换的方向
- (void)p_swichToNewOrientation:(UIInterfaceOrientation)interfaceOrientation {

    NSNumber *orientationTarget = [NSNumber numberWithInteger:interfaceOrientation];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}

经过以上代码,就能实现在 iOS16 之前的设备上进行横竖屏切换,下面开始适配 iOS16 的横竖屏切换

iOS16 实现横竖屏切换

AppDelegate

iOS16 之前方式一样,需要设置 launchScreen 标志变量,重写 launchScreensetter 方法,实现 UIApplicationDelegateapplication:supportedInterfaceOrientationsForWindow: 方法

在需要实现横竖屏切换的 View

p_switchOrientationWithLaunchScreen: 方法中增加 iOS16 适配

/// 切换设备方向
/// - Parameter isLaunchScreen: 是否是全屏
- (void)p_switchOrientationWithLaunchScreen:(BOOL)isLaunchScreen {

    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (isLaunchScreen) {
        // 全屏操作
        appdelegate.launchScreen = YES;
    } else {
        // 退出全屏操作
        appdelegate.launchScreen = NO;
    }

    if (@available(iOS 16.0, *)) {
        // setNeedsUpdateOfSupportedInterfaceOrientations 方法是 UIViewController 的方法,所以这个操作最好是放在控制器中去操作
        [self setNeedsUpdateOfSupportedInterfaceOrientations];
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        // 屏幕方向
        UIInterfaceOrientationMask orientation = isLaunchScreen ? UIInterfaceOrientationMaskLandscapeRight : UIInterfaceOrientationMaskPortrait;
        UIWindowSceneGeometryPreferencesIOS *geometryPreferencesIOS = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientation];
        // 开始切换
        [scene requestGeometryUpdateWithPreferences:geometryPreferencesIOS errorHandler:^(NSError * _Nonnull error) {
            NSLog(@"强制%@错误:%@", isLaunchScreen ? @"横屏" : @"竖屏", error);
        }];
    } else {
        [self p_swichToNewOrientation:isLaunchScreen ? UIInterfaceOrientationLandscapeRight : UIInterfaceOrientationPortrait];
    }
}

如果 Xcode 没有更新到 14,需要采用委婉的方式进行实现

/// 切换设备方向
/// - Parameter isLaunchScreen: 是否是全屏
- (void)p_switchOrientationWithLaunchScreen:(BOOL)isLaunchScreen {

    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (isLaunchScreen) {
        // 全屏操作
        appdelegate.launchScreen = YES;
    } else {
        // 退出全屏操作
        appdelegate.launchScreen = NO;
    }

    if (@available(iOS 16.0, *)) {
        void (^errorHandler)(NSError *error) = ^(NSError *error) {
            NSLog(@"强制%@错误:%@", isLaunchScreen ? @"横屏" : @"竖屏", error);
        };
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        SEL supportedInterfaceSelector = NSSelectorFromString(@"setNeedsUpdateOfSupportedInterfaceOrientations");
        [self performSelector:supportedInterfaceSelector];
        NSArray *array = [[UIApplication sharedApplication].connectedScenes allObjects];
        UIWindowScene *scene = (UIWindowScene *)[array firstObject];
        Class UIWindowSceneGeometryPreferencesIOS = NSClassFromString(@"UIWindowSceneGeometryPreferencesIOS");
        if (UIWindowSceneGeometryPreferencesIOS) {
            SEL initWithInterfaceOrientationsSelector = NSSelectorFromString(@"initWithInterfaceOrientations:");
            UIInterfaceOrientationMask orientation = isLaunchScreen ? UIInterfaceOrientationMaskLandscapeRight : UIInterfaceOrientationMaskPortrait;
            id geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] performSelector:initWithInterfaceOrientationsSelector withObject:@(orientation)];
            if (geometryPreferences) {
                SEL requestGeometryUpdateWithPreferencesSelector = NSSelectorFromString(@"requestGeometryUpdateWithPreferences:errorHandler:");
                if ([scene respondsToSelector:requestGeometryUpdateWithPreferencesSelector]) {
                    [scene performSelector:requestGeometryUpdateWithPreferencesSelector withObject:geometryPreferences withObject:errorHandler];
                }
            }
        }
#pragma clang diagnostic pop
    } else {
        [self p_swichToNewOrientation:isLaunchScreen ? UIInterfaceOrientationLandscapeRight : UIInterfaceOrientationPortrait];
    }
}
横竖屏切换.gif

接下来,讲解一下关于视频的横竖屏切换

场景:竖屏状态,视频只是占了屏幕的一小部分,横屏需要铺满整个屏幕

视频横竖屏切换

先将 redView 占屏幕的一小部分,切换横竖屏效果如下:

视频横竖屏切换.gif

监听横竖屏状态

在这里横屏状态需要铺满整个屏幕,在 iOS16 之前监听 UIDeviceOrientationDidChangeNotification 通知,在监听方法中进行对 redView 的约束更新,但是在 iOS16 开始,这个通知并不会一定有(我这边有时候有,有时候没有通知过来),在找了一遍官方文档之后,发现 UIViewControlleriOS8 开始就有一个方法 viewWillTransitionToSize:withTransitionCoordinator:

/* 
 This method is called when the view controller's view's size is changed by its parent (i.e. for the root view controller when its window rotates or is resized). 
 当 UIViewController 的 view 大小被其父级更改时(即当根控制器的窗口旋转或调整大小时),将调用此方法
 If you override this method, you should either call super to propagate the change to children or manually forward the change to children.
 */
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id )coordinator API_AVAILABLE(ios(8.0));

于是在这里就不需要监听 UIDeviceOrientationDidChangeNotification 通知了

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    NSLog(@"view 发生改变:%@", NSStringFromCGSize(size));
    BOOL isLaunchScreen = NO;
    if (@available(iOS 16.0, *)) {
        // iOS16 需要使用 UIWindowScene 来区分横竖屏
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        isLaunchScreen = scene.interfaceOrientation == UIInterfaceOrientationLandscapeRight;
    } else {
        // 这里是 UIDeviceOrientationLandscapeLeft(我们需要 Home 按键在右边)
        // UIDeviceOrientationLandscapeLeft,       // Device oriented horizontally, home button on the right
        isLaunchScreen = [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft;
    }

    NSLog(@"将要%@", isLaunchScreen ? @"横屏" : @"竖屏");
}

打印信息:

<主>-[YXCLaunchScreenController viewWillTransitionToSize:withTransitionCoordinator:] 47行 : view 发生改变:{812, 375}
<主>-[YXCLaunchScreenController viewWillTransitionToSize:withTransitionCoordinator:] 57行 : 将要横屏
<主>-[YXCLaunchScreenController viewWillTransitionToSize:withTransitionCoordinator:] 47行 : view 发生改变:{375, 812}
<主>-[YXCLaunchScreenController viewWillTransitionToSize:withTransitionCoordinator:] 57行 : 将要竖屏

适配 redView

根据当前屏幕方向对 redView 进行适配,竖屏占屏幕一部分空间,横屏占满整个屏幕

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    
    NSLog(@"view 发生改变:%@", NSStringFromCGSize(size));
    BOOL isLaunchScreen = NO;
    if (@available(iOS 16.0, *)) {
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        isLaunchScreen = scene.interfaceOrientation == UIInterfaceOrientationLandscapeRight;
    } else {
        // 这里是 UIDeviceOrientationLandscapeLeft(我们需要 Home 按键在右边)
        // UIDeviceOrientationLandscapeLeft,       // Device oriented horizontally, home button on the right
        isLaunchScreen = [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft;
    }
    
    NSLog(@"将要%@", isLaunchScreen ? @"横屏" : @"竖屏");
    [self p_updateViewWithIsLaunchScreen:isLaunchScreen size:size];
}
/// 适配横竖屏约束
/// - Parameters:
///   - isLaunchScreen: 是否是横屏
///   - size: 当前控制器 View 的 size 大小
- (void)p_updateViewWithIsLaunchScreen:(BOOL)isLaunchScreen size:(CGSize)size {

    if (isLaunchScreen) {
        // 横屏
        [self.redView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    } else {
        // 竖屏
        [self.redView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.center.left.right.equalTo(self.view);
            make.height.mas_equalTo(150);
        }];
    }
}

最后的效果如图:

视频横竖屏切换最后效果.gif

以上就是关于 iOS16 横竖屏适配以及关于视频适配的全部内容

代码

你可能感兴趣的:(iOS16 横竖屏切换适配)