Search code examples
iphoneiosobjective-cuivieworientation-changes

ios: UIView's width and height after changing orientations is inaccurate?


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!


Solution

  • use the autoresizingMask

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

    then you don't have to write anycode anymore