Sam B
Sam B

Reputation: 27608

Best way to detect iphone orientation

I am making an app where I change the buttons layout depending upon if the user moved his iphone in portrait vs landscape mode. I thought the best place to put my code will be in

-(BOOL) shouldautorotatetointerfaceorientation

But there are two major problems with that

  1. When the page is loaded shouldautorotatetointerfaceorientation is called at least 3 times. I want to execute my code only once.

  2. Even when I move from viewController1 (page1) to viewController2 (page2) with Modal segue and I rotate my iphone on page2 it still calls the autorate code which is in my viewcontroller1. That is very strange.

Anyways, what is the best place to put my orientation based icons in?

Upvotes: 0

Views: 4198

Answers (3)

OdNairy
OdNairy

Reputation: 540

You need to create subclass of UIView and override -(void)layoutSubviews. This message will call when you change orientation or set setNeedsToDisplay. You will get animating changing position for you subviews.
Get current orientation very easy as [[UIApplication sharedApplication] statusBarOrientation]

Upvotes: 1

Ben S
Ben S

Reputation: 69342

UIDevice.orientation;

However, you should still correctly implement the notifications from the rotations of the user. If you want to avoid running your code multiple times unnecessarily, just remember what the last orientation was and only execute your code if it has changed.

Upvotes: 0

PengOne
PengOne

Reputation: 48398

The sole purpose of the method

-(BOOL) shouldautorotatetointerfaceorientation

is to determine which orientations are supported.

If you wish to do custom actions on rotation, then you want to implement one or both of the method

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration

Upvotes: 5

Related Questions