简体   繁体   中英

Always center UIView

I have a small UIView that should appear always in the center of the screen. This works great for portrait mode but does not in landscape.

To draw the UIView I use:

myView.frame = CGRectMake((visibleArea.size.width - MY_VIEW_WIDTH) / 2, (visibleArea.size.height - MY_VIEW_HEIGHT) / 2, MY_VIEW_WIDTH, MY_VIEW_HEIGHT);
myView.autoresizingMask = (
                            UIViewAutoresizingFlexibleTopMargin |
                            UIViewAutoresizingFlexibleBottomMargin |
                            UIViewAutoresizingFlexibleLeftMargin |
                            UIViewAutoresizingFlexibleRightMargin
                           );

Any ideas what might be missing?

Why not try

myView.center = controller.view.center

Is the app auto rotating?

I mean, what does your -[UIViewController shouldAutorotateToInterfaceOrientation:] method looks like? Do you have an initial and supported orientations in your Info.plist file?

Check also parent's view autoresizesSubviews property.

I created a property to give me the bounds, based on the orientation of the device. (This is in a category on UIScreen.)

- (CGRect)boundsWithRespectToOrientation
{
    CGRect bounds = self.bounds;

    if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]) && bounds.size.height > bounds.size.width)
        bounds = CGRectMake(bounds.origin.x, bounds.origin.y, bounds.size.height, bounds.size.width);
    else if (UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) && bounds.size.width > bounds.size.height)
        bounds = CGRectMake(bounds.origin.x, bounds.origin.y, bounds.size.height, bounds.size.width);

    return bounds;
}

Maybe you don't change the orientation of the status bar. If you don't do this, the device thinks that the orientation still portrait, not landscape.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM