当iphone设备方向朝上/朝下时,我可以判断它是风景还是肖像?

Tom*_*eit 18 uiviewcontroller ios uideviceorientation

我得到了这个代码,如果设备是横向左/右或倒置它旋转并显示另一个视图控制器.但如果它朝上或面朝下,那么如何判断它是横向模式还是纵向?因为我只想面朝上或朝下并以横向模式旋转

    - (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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Fré*_*dda 13

interfaceOrientation自iOS 8以来,该属性已被弃用.还有助手方法

UIDeviceOrientationIsPortrait(orientation)  
UIDeviceOrientationIsLandscape(orientation)  
Run Code Online (Sandbox Code Playgroud)

也没有帮助,因为它们在方向时返回false .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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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


Nik*_*uhe 8

在UI代码中,您通常不应该依赖于设备方向,而是依赖于用户界面方向.它们之间通常存在差异,例如,当视图控制器仅支持纵向时.

对于您的情况,最重要的区别是界面方向永远不会面朝上/朝下.

在您的情况下,您可以向视图控制器询问当前用户界面的方向:self.interfaceOrientation.

你的病情可能有点像 if (deviceOrientation is face up/down and interfaceOrientation is landscape)

请记住,设备方向横向左侧表示用户界面方向横向右侧.