I'm trying to make sure my custom UIView is always on the center of the screen even after orientation changes.

So I was trying to do some math with my UIView's superview, which is the main view of my program (so it takes up the whole screen).

I noticed when printing out the superview's frame's width and height after the orientation change that it's width and height don't change after the first rotation then is not what I would expect afterwards.

By unexpected I mean, when the device is in portrait mode, width = 480 and height = 320. When the device is in landscape mode, width = 320 and height = 480.

I'm getting these numbers from:

CGRect sFrame = [self superview].frame;
NSLog(@"width = %f, height = %f", sFrame.size.width, sFrame.size.height);

This is in my custom UIView.

Is the superview's frames not automatically updated? If not, where should I look to get an accurate width and height? Is there a better way to do this?

Thank you very much!

有帮助吗?

解决方案

use the autoresizingMask

view.center = view.superview.center;
view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin |  UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;

then you don't have to write anycode anymore

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top