如何在没有[UIDevice setValue:forKey:@“orientation”]的情况下更改UI方向

时间:2016-09-29 16:46:51

标签: ios orientation

我的目标是使用按钮更改锁定/解锁方向。在锁定模式下,可以通过按钮切换方向,在解锁模式下,方向由传感器确定 我尝试使用 static void SetBasicAuthHeader( WebRequest request, String userName, String userPassword ) { string authInfo = userName + ":" + userPassword; authInfo = Convert.ToBase64String( Encoding.GetEncoding( "ISO-8859-1" ).GetBytes( authInfo ) ); request.Headers[ "Authorization" ] = "Basic " + authInfo; } 实现此目的,但此代码存在问题 假设我的应用程序目前是“锁定模式,纵向UI,纵向设备”。然后我将设备旋转到横向左侧,并解锁方向。我预计[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:orientation] forKey:@"orientation"]应为[[UIDevice currentDevice] orientation]。但是价值是UIDeviceOrientationLandscapeLeft,虽然真实的设备是景观!

我还尝试了通知中心,代码如下。

UIDeviceOrientationPortrait

但此代码无法正常运行。如果设备处于横向状态,并且[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDeviceOrientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil]; 将UI方向设置为纵向,则在将设备旋转为纵向时不会调用[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIDeviceOrientationPortrait]。我认为设备的方向值已经设置为纵向(通过我的代码,而不是传感器)。

PS。当然,我选中了必需的全屏选项。

编辑:了解如何获取不受onDeviceOrientationChanged影响的设备真实定位也是一个很好的答案。

1 个答案:

答案 0 :(得分:4)

我使用MotionManager解决了这个问题。当我锁定(或更改)方向时,[[UIDevice currentDevice] setValue:[NSNumber numberWithInt:orientation] forKey:@"orientation"]就像往常一样 但是,当我解锁方向时,我使用MotionManager使用以下代码刷新了方向。

CMMotionManager motionManager = [[CMMotionManager alloc] init];

[motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
    withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
        [motionManager stopAccelerometerUpdates];

        CMAcceleration acceleration = accelerometerData.acceleration;
        UIInterfaceOrientation orientation;
        if (acceleration.x >= 0.75) {
            orientation = UIInterfaceOrientationLandscapeLeft;
        } else if (acceleration.x <= -0.75) {
            orientation = UIInterfaceOrientationLandscapeRight;
        } else if (acceleration.y <= -0.75) {
            orientation = UIInterfaceOrientationPortrait;
        } else if (acceleration.y >= 0.75) {
            orientation = UIInterfaceOrientationPortraitUpsideDown;
        } else {
            return;
        }
        [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:orientation]
                            forKey:@"orientation"];
        [UINavigationController attemptRotationToDeviceOrientation];
    }];

当然,您应该了解supportedInterfaceOrientationsshouldAutorotate方法。