0
if(UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
   NSLog(@"Device is in portrait");
} else if(UIInterfaceOrientationIsLandscape(self.interfaceOrientation)){
   NSLog(@"Device is in landscape");
}
NSLog(@"View bounds are %@",NSStringFromCGRect(self.view.bounds));

I call this code from viewDidLoad and then subsequently from a gesture recognizer. When in landscape mode, the output from viewDidLoad is:

2013-01-04 20:44:48.925 293 Calendar[2638:907] Device is in landscape
2013-01-04 20:44:48.926 293 Calendar[2638:907] View bounds are {{0, 0}, {748, 1024}}

When called from the swipe gesture recognizer the output is:

2013-01-04 20:44:58.002 293 Calendar[2638:907] Device is in landscape
2013-01-04 20:44:58.004 293 Calendar[2638:907] View bounds are {{0, 0}, {1024, 748}}

If the device is in landscape both times, why are the dimensions opposite? Should I be looking at view dimensions elsewhere than viewDidLoad? What event would that be?

I tried viewWillAppear, and it was the same as viewDidLoad. I tried viewDidAppear, and it was the same as from the gesture recognizer. So I assume that's what I should use instead of viewDidLoad for the proper view dimensions. Correct?

Victor Engel
  • 2,037
  • 2
  • 25
  • 46

1 Answers1

1

The viewDidLoad method is called before the view controller's view has been properly sized. It is normal for the view's size to appear incorrect at this time.

The proper place to deal with all of this is the viewWillLayoutSubviews. The view's size and orientation are up to date as a result of an initial display or due to an orientation change. This is where you should update any subviews that are not properly handled with some sort of auto-layout.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thank you. I think that's what I needed. BTW, is there a document that outlines the flow of these methods? – Victor Engel Jan 05 '13 at 04:40
  • Maybe this is not what I want. The code I need triggered needs to be called from elsewhere, too, for example, a swipe gesture. The thing is, when I call the code from the swipe gesture, that triggers a call to viewWillLayoutSubview, so it ends up being called twice. There's something in the code (probably adding subviews) that triggers viewWillLayoutSubviews. Is there something I can set to trigger that method directly? – Victor Engel Jan 05 '13 at 22:45
  • I found [an interesting article](http://kevin.dew.name/post/18579273258/where-to-progmatically-lay-out-views-in-ios-5-and) about the various places to put code. I'm going to study it carefully before I make another decision. – Victor Engel Jan 05 '13 at 22:55