Reputation: 1027
I am just trying to set a width and a height constraint on my imgView. I have the following code:
UIImageView *imgView = [[UIImageView alloc] init];
imgView.center = self.view.center;
imgView.image = [UIImage imageNamed:@"favorites5-highlighted.png"];
imgView.contentMode = UIViewContentModeCenter;
[self.view addSubview:imgView];
// width constraint
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[imgView(==100)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(imgView)]];
// height constraint
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[imgView(==100)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(imgView)]];
I end up getting this error: Unable to simultaneously satisfy constraints. I looked up SO and tried adding:
imgView.translatesAutoresizingMaskIntoConstraints = NO;
and
self.view.translatesAutoresizingMaskIntoConstraints = NO;
EDIT:
I am just trying to set the width and height of the imageView to the desired properties. I first tried using
CGRect rect = CGRectMake(0, 0, 10, 10);
imgView.frame = rect;
but nothing changed
Upvotes: 2
Views: 3137
Reputation: 437872
Two issues:
You do want:
imgView.translatesAutoresizingMaskIntoConstraints = NO;
You do not want:
self.view.translatesAutoresizingMaskIntoConstraints = NO;
Your attempt to set center
is for naught, as when constraints are applied, this will be lost. Unfortunately, you don't define constraints to define the location of the image view. You might do that with the last two lines of the block below:
UIImageView *imgView = [[UIImageView alloc] init];
//imgView.center = self.view.center; // this does nothing in auto layout
imgView.image = [UIImage imageNamed:@"favorites5-highlighted.png"];
imgView.contentMode = UIViewContentModeCenter;
imgView.translatesAutoresizingMaskIntoConstraints = NO; // add this line
[self.view addSubview:imgView];
NSDictionary *views = NSDictionaryOfVariableBindings(imgView);
// width constraint
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[imgView(100)]" options:0 metrics:nil views:views]];
// height constraint
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[imgView(100)]" options:0 metrics:nil views:views]];
// center align
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:imgView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:imgView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]];
Upvotes: 11