How to check in which position (landscape or portrait) is the iPhone now?

后端 未结 13 1007
旧巷少年郎
旧巷少年郎 2021-01-30 06:47

I have an app with a tab bar, and nav controllers in each tab. When user shakes the device, a UIImageView appears as a child view in the nav controller. But the

13条回答
  •  清歌不尽
    2021-01-30 07:38

    You could check it like so (Swift 3):

    var isPortrait: Bool {
      let orientation = UIDevice.current.orientation
      switch orientation {
        case .portrait, .portraitUpsideDown:
          return true
    
        case .faceUp, .faceDown:
          // Check the interface orientation
          let interfaceOrientation = UIApplication.shared.statusBarOrientation
          switch interfaceOrientation{
            case .portrait, .portraitUpsideDown:
              return true
            default:
              return false
          }
       default: // .unknown
         return false // not very satisfying to return false as if we were in landscape :-/
       }
    }
    

    If you are in a ViewController, you can also do like so (that is what I ended up doing):

    private 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
            return self.view.width < self.view.height
        }
    }
    

    Although even this should be enough in that case:

    private var isPortrait: Bool {
         return self.view.width < self.view.height
    }
    

提交回复
热议问题