Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect rotation changes in iOS

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.

like image 988
Undo Avatar asked Jan 16 '13 22:01

Undo


People also ask

How do you check rotation on iPhone?

Swipe down from the top-right corner of your screen to open Control Center. Tap the Portrait Orientation Lock button to make sure that it's off.

Which method called when orientation changes IOS?

This inherited UIViewController method which can be overridden will be trigger every time the interface orientation will be change. Consequently you can do all your modifications in the latter. By implementing this method you'll then be able to react to any change of orientation to your interface.


4 Answers

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.

like image 84
Levi Avatar answered Sep 24 '22 05:09

Levi


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

like image 21
Stephen H King Avatar answered Sep 24 '22 05:09

Stephen H King


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`
    })
}
like image 37
PatrickDotStar Avatar answered Sep 23 '22 05:09

PatrickDotStar


Swift 3:

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

}
like image 27
GetSwifty Avatar answered Sep 24 '22 05:09

GetSwifty