19

我得到了这段代码,如果设备处于横向左/右或倒置状态,它会旋转并显示另一个视图控制器。但是如果它的方向是朝上还是朝下,那么我怎么知道它是横向模式还是纵向模式?因为我只想在它朝上或朝下并处于横向模式时旋转

    - (void)viewDidAppear:(BOOL)animated
    {
        UIDeviceOrientation orientation = [[UIDevice currentDevice]orientation];
        NSLog(@"orientation %d", orientation);
        if ((orientation == 2) || (orientation == 3) || (orientation == 4))
        {

            [self performSegueWithIdentifier:@"DisplayLandscapeView" sender:self];
            isShowingLandscapeView = YES;
    }
}
4

4 回答 4

16

自 iOS 8 起,该interfaceOrientation属性已被弃用。还有 helpers 方法

UIDeviceOrientationIsPortrait(orientation)  
UIDeviceOrientationIsLandscape(orientation)  

也无济于事,因为当方向为.faceUp.

所以我以这种方式结束了检查:

extension UIViewController {
    var isPortrait: Bool {
        let orientation = UIDevice.current.orientation
        switch orientation {
        case .portrait, .portraitUpsideDown:
            return true
        case .landscapeLeft, .landscapeRight:
            return false
        default: // unknown or faceUp or faceDown
            guard let window = self.view.window else { return false }
            return window.frame.size.width < window.frame.size.height
        }
    }
}

这是在 UIViewController 扩展中,所以如果其他一切都失败了,我可以恢复比较屏幕宽度和高度。

我使用window是因为如果当前 ViewController 嵌入在容器中,它可能无法反映全局 iPad 方向。

于 2017-09-20T12:57:25.143 回答
9

In UI code you usually should not depend on the device orientation but the user interface orientation. There's often a difference between them, for example when a view controller only supports portrait.

The most important difference for your case is that the interface orientation is never face up/down.

In your case you can just ask the view controller for the current user interface orientation: self.interfaceOrientation.

Your condition could be expressed somewhat like if (deviceOrientation is face up/down and interfaceOrientation is landscape)

Bear in mind that a device orientation landscape left means a user interface orientation landscape right.

于 2013-09-11T13:42:44.107 回答
3

是的,您可以,这UIDeviceOrientation是一个枚举,其中包含:

 UIDeviceOrientationUnknown,
 UIDeviceOrientationPortrait,          
 UIDeviceOrientationPortraitUpsideDown,
 UIDeviceOrientationLandscapeLeft,     
 UIDeviceOrientationLandscapeRight,    
 UIDeviceOrientationFaceUp,            
 UIDeviceOrientationFaceDown    

甚至还有两个助手:

UIDeviceOrientationIsPortrait(orientation)  
UIDeviceOrientationIsLandscape(orientation) 

只需 cmd onUIDeviceOrientation即可显示声明枚举的头文件。

于 2013-09-11T13:42:30.753 回答
3

有一种方法可以检查它。

UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];
UIInterfaceOrientation statusBarOrientation =[UIApplication sharedApplication].statusBarOrientation;

使用第一个检查设备是否正面朝上,第二个将告诉您设备是纵向还是横向。

于 2015-12-12T09:24:25.003 回答