Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect orientation change?

People also ask

How do you know if orientation changes?

use android:configChanges="orientation|screenSize" instead of android:configChanges="orientation|keyboardHidden" in your manifest file and check ... !!!

How can we detect the orientation of the screen?

Detecting Orientation Changes in Javascript Should you need to simply detect when a user changes orientation, you can use the following event listener: screen. orientation. addEventListener("change", function(e) { // Do something on change });

What happens to an activity when the screen orientation changes?

When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them. Android does this so that your application can reload resources based on the new configuration.


Here's how I got it working:

In AppDelegate.swift inside the didFinishLaunchingWithOptions function I put:

NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.rotated), name: UIDevice.orientationDidChangeNotification, object: nil)

and then inside the AppDelegate class I put the following function:

func rotated() {
    if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) {
        print("Landscape")
    }

    if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) {
        print("Portrait")
    }
}

Hope this helps anyone else!

Thanks!


According to the Apple docs:

This method is called when the view controller's view's size is changed by its parent (i.e. for the root view controller when its window rotates or is resized).

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    }
    if UIDevice.current.orientation.isFlat {
        print("Flat")
    } else {
        print("Portrait")
    }
}

I need to detect rotation while using the camera with AVFoundation, and found that the didRotate (now deprecated) & willTransition methods were unreliable for my needs. Using the notification posted by David did work, but is not current for Swift 3.x & above.

The following makes use of a closure, which appears to be Apple's preference going forward.

var didRotate: (Notification) -> Void = { notification in
        switch UIDevice.current.orientation {
        case .landscapeLeft, .landscapeRight:
            print("landscape")
        case .portrait, .portraitUpsideDown:
            print("Portrait")
        default:
            print("other (such as face up & down)")
        }
    }

To set up the notification:

NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification,
                                       object: nil,
                                       queue: .main,
                                       using: didRotate)

To tear down the notification:

NotificationCenter.default.removeObserver(self,
                                          name: UIDevice.orientationDidChangeNotification,
                                          object: nil)

Regarding the deprecation statement, my initial comment was misleading, so I wanted to update that. As noted, the usage of @objc inference has been deprecated, which in turn was needed to use a #selector. By using a closure instead, this can be avoided and you now have a solution that should avoid a crash due to calling an invalid selector.


Using -orientation property of UIDevice is not correct (even if it could work in most of cases) and could lead to some bugs, for instance UIDeviceOrientation consider also the orientation of the device if it is face up or down, there is no direct pair in UIInterfaceOrientation enum for those values.
Furthermore, if you lock your app in some particular orientation, UIDevice will give you the device orientation without taking that into account.
On the other side iOS8 has deprecated the interfaceOrientation property on UIViewController class.
There are 2 options available to detect the interface orientation:

  • Use the status bar orientation
  • Use size classes, on iPhone if they are not overridden they could give you a way to understand the current interface orientation

What is still missing is a way to understand the direction of a change of interface orientation, that is very important during animations.
In the session of WWDC 2014 "View controller advancement in iOS8" the speaker provides a solution to that problem too, using the method that replaces -will/DidRotateToInterfaceOrientation.

Here the proposed solution partially implemented, more info here:

func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        let orientation = orientationFromTransform(coordinator.targetTransform())
        let oldOrientation = UIApplication.sharedApplication().statusBarOrientation
        myWillRotateToInterfaceOrientation(orientation,duration: duration)
        coordinator.animateAlongsideTransition({ (ctx) in
            self.myWillAnimateRotationToInterfaceOrientation(orientation,
            duration:duration)
            }) { (ctx) in
                self.myDidAnimateFromInterfaceOrientation(oldOrientation)
        }
    }

I know this question is for Swift, but since it's one of the top links for a Google search and if you're looking for the same code in Objective-C:

// add the observer
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rotated:) name:UIDeviceOrientationDidChangeNotification object:nil];

// remove the observer
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];

// method signature
- (void)rotated:(NSNotification *)notification {
    // do stuff here
}

Easy, this works in iOS8 and 9 / Swift 2 / Xcode7, just put this code inside your viewcontroller.swift. It will print the screen dimensions with every orientation change, you can put your own code instead:

override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
        getScreenSize()
    }
    var screenWidth:CGFloat=0
    var screenHeight:CGFloat=0
    func getScreenSize(){
        screenWidth=UIScreen.mainScreen().bounds.width
        screenHeight=UIScreen.mainScreen().bounds.height
        print("SCREEN RESOLUTION: "+screenWidth.description+" x "+screenHeight.description)
    }