1

我已经为此工作了一段时间,并在谷歌上搜索了我能想到的所有相关内容。

我的应用程序中有一个按钮可以切换旋转。当我关闭旋转,旋转设备,然后重新打开旋转时,我需要一种将应用程序方向匹配回设备方向的方法。

@interface ViewController ()
{
    BOOL _rotationStatus;
}

与按钮按下相关的方法:

   -(void)toggleRotation
    {
        if(_rotationStatus == NO)
        {        
            _rotationStatus = YES;
        }
        else
        {
            _rotationStatus = NO;
        }
    }


- (BOOL)shouldAutorotate //only targeting iOS 6
{
    return !_rotationStatus;
}

这可以很好地切换旋转,但是当重新打开旋转时,方向不会“刷新”以匹配设备方向,直到您再次旋转设备。

例如

  1. 设备和应用程序以纵向启动。
  2. 点击按钮将旋转切换为关闭。
  3. 将设备旋转到横向。
  4. 设备是横向的,应用程序是纵向的,正如预期的那样。
  5. 点击按钮将旋转切换为开启

期望:应用旋转到横向以匹配设备。

实际:应用程序保持纵向,直到收到另一个轮换通知。

我认为纠正此问题的一种方法是检查设备方向,并检查应用程序方向并在旋转切换回打开时匹配它们。

我将此添加到方法中:

if ((UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) && ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait))
        {
            NSLog(@"mis-matched Device and App orientations");
            //do the rotation?
            [[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationLandscapeRight animated:YES];
        }

所以完整的方法看起来像这样。

-(void)toggleRotation
{
        if(_rotationStatus == NO)
        {        
            _rotationStatus = YES;
        }
        else
        {
            _rotationStatus = NO;

            if ((UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)) && ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait))
          {
              NSLog(@"mis-matched Device and App orientations");
              //do the rotation?
              [[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationLandscapeRight animated:YES];
          }
        }
}

NSLog 在我期望的时候打印,但是对 setStatusBarOrientation 的调用不会导致旋转。

我是 iOS 菜鸟,所以我确信我做错了很多事情。有一个更好的方法吗?

4

0 回答 0