Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a UIImageView, center vertically in container with constraints programmatically

I want to center UIImageView (self.showImageView) in container view (self.view)

I tried below code it did't work:

NSLayoutConstraint *xCenterConstraint = [NSLayoutConstraint constraintWithItem:self.showImageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
[self.view addConstraint:xCenterConstraint];

NSLayoutConstraint *yCenterConstraint = [NSLayoutConstraint constraintWithItem:self.showImageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
[self.view addConstraint:yCenterConstraint];
like image 694
iTamilan Avatar asked Dec 15 '14 11:12

iTamilan


2 Answers

Try this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];
    redView.backgroundColor = [UIColor redColor];
    redView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:redView];
    [redView addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:100]];
    [redView addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:200]];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:redView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
    [self.view addSubview:redView];
}
like image 90
Vitalii Gozhenko Avatar answered Oct 13 '22 19:10

Vitalii Gozhenko


Try

self.showImageView.center=self.view.center;

This will do your work by setting self.showImageView to the center of self.view.

like image 38
Sudhin Davis Avatar answered Oct 13 '22 19:10

Sudhin Davis