简体   繁体   中英

How do I center a UIImageView either programmatically or in the storyboard

I have an Image View that I want to center on both the 3.5 and the 4 inch screens. For some reason this is proving to be impossible. I have no idea why I'm struggling with this, it seems so basic.

Is it possible, using constraints or something, to say "center the image on both screens" because it is centered on the iPhone 5, but on the 4, it's aligned with the top, and it cuts off the bottom of the image, because the image is the size of an iPhone 5 screen.

If you want to do it without auto layout and constraints then programatically it would be something like this.

UIImage *yourImage     = ....
UIImageView *imageView = [[UIImageView alloc] initWithImage:yourImage];
[self.view addSubview:imageView];

CGSize superviewSize = imageView.superview.frame.size;
imageView.center     = CGPointMake((superviewSize.width / 2), (superviewSize.heigth / 2));

Go to your Storyboard file. Select your UIImageView and control-drag to it's superview. You should then be presented with a few options. Click on "Center Horizontally in Container" and then repeat for "Center Vertically in Container.

If you want to have the UIImageView cover the whole superview then click on "Leading Space to Container Margin" and repeat for "Trailing Space to Container Margin", "Top Space to Top Layout Guide" and "Bottom Space to Bottom Layout Guide" instead.

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