RJE
RJE

Reputation: 891

Detect iOS device orientation change without rotating view

I have a UIViewController and I wanna detect the device orientation changes on that ViewController. But I do not want to rotate the view. My app supports all orientations but this ViewController should keep portrait mode all the time.

I can set supportedInterfaceOrientations to portrait only to get the desired functionality. But I still wanna know the orientation changes within this ViewController. Normally I can get the event with the viewWillTransition method or traitCollectionDidChange method. But when I set supportedInterfaceOrientations to portrait none of those methods get called.

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

    // this method never get called
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
    }

Is there a way to detect the device orientation changes when I set supportedInterfaceOrientations to portrait only?

Upvotes: 0

Views: 987

Answers (2)

ItsAlwaysThere
ItsAlwaysThere

Reputation: 109

Heres one way to do it.

        
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
          //  return UIInterfaceOrientationMask.all } else{ }
        return self.orientationLock
    }

Then for viewController you want to change the desired orientation allowed

   AppDelegate.AppUtility.lockOrientation(.portrait, andRotateTo: .portrait)
   

Upvotes: 0

Pastre
Pastre

Reputation: 743

I think you can subscribe to a notification

final class ViewController {
    override func viewDidLoad() {
        super.viewDidLoad() 
        NotificationCenter.default.addObserver(self, #selector(handleOrientationChange, name: UIDevice.orientationDidChangeNotification, object: nil))
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    @objc
    private func handleOrientationChange() {
        // Yay, orientation changed!
    }
}

Upvotes: 2

Related Questions