iOS 动态控制屏幕旋转

7 篇文章 0 订阅

本文讲述动态控制自动旋转方向(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);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值