适配iOS16横竖屏切换问题。

 

//Button点击全屏,强制横屏
-(void)fullScreenAction{
    if (@available(iOS 16, *)) {
        _landscape = YES;
        [self setNeedsUpdateOfSupportedInterfaceOrientations];
    }
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (_landscape)
    {
        //横屏
        return UIInterfaceOrientationMaskLandscape;
    }else
    {
        //竖屏
        return UIInterfaceOrientationMaskPortrait;
    }
}
//点击竖屏
-(void)backButtonActionCB{
    if (@available(iOS 16, *)) {
        _landscape = NO;
        [self setNeedsUpdateOfSupportedInterfaceOrientations];
    }
}

//原来的方法添加兼容iOS16的方法

- (void)interfaceOrientation:(UIInterfaceOrientation)orientation {
    NSLog(@"interfaceOrientation:%ld",(long)orientation);
    if (@available(iOS 16.0, *)) {
        // setNeedsUpdateOfSupportedInterfaceOrientations 方法是 UIViewController 的方法
//        [self setNeedsUpdateOfSupportedInterfaceOrientations];
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        // 屏幕方向 UIInterfaceOrientationMask
        UIInterfaceOrientationMask orientation22 = !(orientation == UIInterfaceOrientationPortrait) ? UIInterfaceOrientationMaskLandscape: UIInterfaceOrientationMaskPortrait;
        UIWindowSceneGeometryPreferencesIOS *geometryPreferencesIOS = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientation22];
        // 开始切换
        [scene requestGeometryUpdateWithPreferences:geometryPreferencesIOS errorHandler:^(NSError * _Nonnull error) {
            NSLog(@"错误:%@", error);
        }];
    }else{
        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 = orientation;
            [invocation setArgument:&val atIndex:2];
            [invocation invoke];
        }
        [UIViewController attemptRotationToDeviceOrientation];
    }
}

 

posted @ 2022-11-01 17:41  frounk  阅读(860)  评论(0编辑  收藏  举报