When I start my ViewController in landscape
mode (After viewDidLoad is called), I print the frame it's giving me the frame size for portrait mode instead.
Is this a bug any suggestions?
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@", NSStringFromCGRect(self.view.frame));
// Result is (0, 0 , 768, 1024)
}
Here's a clean solution.
I was experiencing the same issue and I insist on using
frame
throughout my app. I do not want to make an exception for the root view controller. I noticed that the root view controller'sframe
was displaying portrait dimensions, but all subviews had correct landscape dimensions.Since it is only the root view controller that behaves differently, we can set a standard, blank view controller as the root view controller and add our custom view controller to that. (Code below.)
You can then use
frame
as you intend to, in your custom view controller.There are a couple of things that you don't understand.
First, the system sends you
viewDidLoad
immediately after loading your nib. It hasn't even added the view to the view hierarchy yet. So it hasn't resized your view based on the device's rotation either.Second, a view's frame is in its superview's coordinate space. If this is your root view, its superview will be the
UIWindow
(once the system actually adds your view to the view hierarchy). TheUIWindow
handles rotation by setting the transform of its subview. This mean that the view's frame will not necessarily be what you expect.Here's the view hierarchy in portrait orientation:
and here's the view hierarchy in landscape-left orientation:
Notice that in landscape orientation, the frame size is 748 x 1024, not 1024 x 748.
What you probably want to look at, if this is your root view, is the view's bounds:
Presumably you want to know when the view's transform, frame, and bounds get updated. If the interface is in a landscape orientation when your view controller loads its view, you will receive messages in this order:
You can see that your view's bounds change after you receive
willRotateToInterfaceOrientation:duration:
and before you receiveviewWillLayoutSubviews
.The
viewWillLayoutSubviews
andviewDidLayoutSubviews
methods are new to iOS 5.0.The
layoutSubviews
message is sent to the view, not the view controller, so you will need to create a customUIView
subclass if you want to use it.