Detect rotation changes in iOS
Asked Answered
M

4

19

I am making an iOS app that needs to do a little interface rearrangement upon rotation. I am trying to detect this by implementing - (void)orientationChanged:(NSNotification *)note, but this gives me notifications for when the device is face up or face down.

I want a way to just get notified when the interface changes orientations.

Magnetics answered 16/1, 2013 at 22:41 Comment(0)
C
24

Since iOS 8, above methods were deprecated, and the proper way to handle and detect device rotation is:

-(void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id )coordinator;

To detect device orientation, you should (according to documentation): call the statusBarOrientation method to determine the device orientation

Coronado answered 30/5, 2016 at 18:50 Comment(0)
F
28

There are several method where you can do that, you can find them in the UIViewController class reference:

– willRotateToInterfaceOrientation:duration:
– willAnimateRotationToInterfaceOrientation:duration:
– didRotateFromInterfaceOrientation:

You could also do it in the viewWillLayoutSubviews method, but be careful with it, because it is called on the screen appearance too, and whenever you add a subview.

Edit:

Solution now deprecated, see accepted answer.

Ferromagnetic answered 16/1, 2013 at 22:47 Comment(1)
Note that all three of those are deprecated in iOS 8. They recommend using a variant that transitions to size instead.Guenevere
C
24

Since iOS 8, above methods were deprecated, and the proper way to handle and detect device rotation is:

-(void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id )coordinator;

To detect device orientation, you should (according to documentation): call the statusBarOrientation method to determine the device orientation

Coronado answered 30/5, 2016 at 18:50 Comment(0)
D
9

Since iOS 8 this is the correct way to do it.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    coordinator.animate(alongsideTransition: { context in
        // This is called during the animation
    }, completion: { context in
        // This is called after the rotation is finished. Equal to deprecated `didRotate`
    })
}
Descender answered 12/2, 2018 at 8:37 Comment(0)
E
5

Swift 3:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

}
Enduring answered 9/1, 2017 at 21:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.