简体   繁体   中英

Add UIImageView inside UIView at exactly centre of the view

I add UIView which has the size equal to screen size than I add UIImageView to this view. I want to set this UIImageView at exactly centre of the UIView . I'm doing this programatically therefore, can't put constraints via storyboard. Below is my code:

UIView* viewForImage = [[UIView alloc] initWithFrame:screenRect];
CGRect rect = CGRectMake(0, 0, 100, 200);
UIImageView* imgcoverView = [[UIImageView alloc] initWithFrame:rect];
imgcoverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.9];
imgcoverView.image = imgView.image;
[viewForImage addSubview:imgcoverView];
imgcoverView.center = CGPointMake(viewForImage.frame.size.width/2,viewForImage.frame.size.height/2) ;

Please consider different orientation of the device. I think it's better to add as two centre constraints.

NSLayoutConstraint *xCenterConstraint = [NSLayoutConstraint constraintWithItem:imgcoverView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:viewForImage attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
[viewForImage addConstraint:xCenterConstraint];

NSLayoutConstraint *yCenterConstraint = [NSLayoutConstraint constraintWithItem:imgcoverView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:viewForImage attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
[viewForImage addConstraint:yCenterConstraint];

You can Do it By constraint !!!

set only two Constraint Horizontal center in container and Vertical center in container

imgcoverView.frame = 
           CGRectMake(viewForImage.frame.origin.x + (viewForImage.frame.size.width - imgcoverView.frame.size.width)/2, 
                      viewForImage.frame.origin.y + (viewForImage.frame.size.height - imgcoverView.frame.size.height)/2,
                      imgcoverView.frame.size.width,
                      imgcoverView.frame.size.height);

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