skip to Main Content

I want an app to maintain the same UI despite of what the device orientation is. I don’t want the default behavior when supporting multiple device orientations where the UI slides / shifts automatically each time the orientation changes. However, I also want to detect what the orientation is in order to perform some custom code.

  • UIDevice.orientationDidChangeNotification doesn’t seem to get sent when supportedDeviceOrientations in Info.plist is set to only portrait.
  • Overriding supportedInterfaceOrientations didn’t seem to do anything.

Is there a way to get information on the device’s orientation (it WOULD have been in landscape right now) while only allowing for one device orientation in Info.plist?

2

Answers


  1. What you need to do is update your Info.plist to support all orientations.

    Then in your root view controller you override supportedInterfaceOrientations:

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    

    This keeps your view controller in portrait regardless of the device orientation but it also allows device orientation change notifications to still be sent as the device orientation changes.

    This assumes that rotation lock is not enabled on the iPhone. If the user locks the rotation then an app can’t get device orientation change notifications at all. But that’s basically the point of the rotation lock.

    Login or Signup to reply.
  2. Assuming you take in place @hangarrash answer, to detect iPhone orientation you can use NotificationCenter and some combine publisher.

    import Combine
    ...
    private let cancellables: Set<AnyCancellable> = []
    ...
    NotificationCenter
                .default
                .publisher(for: UIDevice.orientationDidChangeNotification)
                .sink { [weak self] _ in
                    
                    let orientation = UIDevice.current.orientation
                    switch orientation {
                    case .unknown:
                        ...
                    case .portrait:
                        ...
                    case .portraitUpsideDown:
                        ...
                    case .landscapeLeft:
                        ...
                    case .landscapeRight:
                        ...
                    case .faceUp:
                        ...
                    case .faceDown:
                        ...
                    @unknown default: break
                    }
                }
                .store(in: &cancellables)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search