I want to do some layout change when the devices rotate. So I implement - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration method to do the work. But I realize when this method is called the self.view.frame and self.view.bounds are different. The self.view.bounds.size is correct and the self.view.frame.size seems still not rotate.
For example, I created an empty singleView Project and implemented the method like follows:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
NSLog(@"willAnimateRotationToInterfaceOrientation");
NSLog(@"self.view.bounds.size width:%f height:%f ",self.view.bounds.size.width,self.view.bounds.size.height);
NSLog(@"self.view.frame.size width:%f height:%f",self.view.frame.size.width,self.view.frame.size.height);
}
when the device rotates from portrait to landscape. the output is as follows:
2013-06-11 11:57:46.959 viewDemo[95658:707] willAnimateRotationToInterfaceOrientation
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.bounds.size width:1024.000000 height:748.000000
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.frame.size width:748.000000 height:1024.000000
I wonder why these sizes are different? They shouldn't be always the same? And when to choose which one to use?
Any help will be appreciated.
Look at the answer by "tc.", which is accepted as of now. Copying few lines from that answer to here.
So, the "frame" is relative to the parent view, which in this case is the UIWindow. When you rotate device, the window doesn't rotate; the view controller's view does. From the window's perspective, everything is effectively in portrait mode. This is why even after device is rotated to landscape, self.view.frame will not change.
You should use self.view.bounds to perform any calculation as it gives you the correct values independent of your device orientation.
I wonder why these values are different? They shouldn't be always the same?
The bounds of an UIView is the rectangle, expressed as a location (x, y) and size (width, height) relative to its own coordinate system (0,0).
The frame of an UIView is the rectangle, expressed as a location (x, y) and size (width, height) relative to the superview it is contained within.
In the case of the bounds, the x and y coordinates are at 0,0 as these coordinates are relative to the view itself. However, the frame x and y coordinates are relative to the position of the view within the parent view
And when to choose which one to use?
Hopefully this helps clarify the circumstances where each property might get used.
UIView's frame, bounds, center, origin, when to use what?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With