iOS 动态控制屏幕旋转

本文讲述动态控制自动旋转方向(1到3),手动旋转屏幕方向(第4),以及通过旋转vc的view假旋转屏幕方向。

1.配置vc可以旋转

在需要配置方向的vc中 覆盖这个函数

- (BOOL)shouldAutorotate {
    
    
        return YES;
}

2.vc可以旋转的方向

在需要配置方向的vc中 覆盖这个函数,返回值可以动态改动,来实现手动控制屏幕旋转方向

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    
    
    return UIInterfaceOrientationMaskAll;
}

3.可能需要配置应用方向

在AppDelegate中覆盖这个函数,返回值可以动态改动,来实现手动控制屏幕旋转方向

- (UIInterfaceOrientationMask)  application:(UIApplication *)application
    supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    
    
    return UIInterfaceOrientationMaskAll;
}

当配置了以上所有步骤,其实屏幕就可以自动旋转方向了,可以旋转的方向就是他们返回的值。

3.手动旋转方向

 [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    
    UIInterfaceOrientationMask orientationMask = UIInterfaceOrientationMaskLandscapeRight;
    UIDeviceOrientation deviceOrientation = UIDeviceOrientationLandscapeRight;
        if (@available(iOS 16.0, *)) {
    
    
        [self setNeedsUpdateOfSupportedInterfaceOrientations];
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        UIWindowSceneGeometryPreferencesIOS *geometryPreferencesIOS = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientationMask];
        
        [scene requestGeometryUpdateWithPreferences:geometryPreferencesIOS
                                       errorHandler:^(NSError *_Nonnull error) {
    
    
            NSLog(@"屏幕旋转 错误:%@", error);
            
        }];
    } else {
    
    
        [[UIDevice currentDevice] setValue:@(deviceOrientation) forKey:@"orientation"];
        [UIViewController attemptRotationToDeviceOrientation];
    }
    
     [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];

需要注意的点是,当手动旋转的时候需要配合修改vc支持方向和应用返回方向的值,这样才能转过去。之所以不使用所有方向,是因为自动旋转会进行干扰,比如屏幕在物理当前是竖直状态,自动旋转就会旋转到竖直,手动旋转可能就会失败哟。

4.旋转VIew

  如果不想像上面那样麻烦控制,直接旋转View也是一个旋转屏幕的方法。但是这个方法有个问题是,设备方向没有真正旋转,所以状态栏方向可能是错的,下拉锁屏方向看起来也会有些异常。
- (BOOL)prefersStatusBarHidden {
    
    
    return _isRight;
}


-(void)changeOrientationRight {
    
    
    //设备方向没有转动,所以状态栏方向是错的,要隐藏
    _isRight = YES;
    [self setNeedsStatusBarAppearanceUpdate];
    
    self.view.transform = CGAffineTransformMakeRotation(M_PI/2);
    CGSize size = UIScreen.mainScreen.bounds.size;
    self.view.bounds = CGRectMake(0, 0, size.height, size.width);
}

猜你喜欢

转载自blog.csdn.net/htwhtw123/article/details/128724056
今日推荐