Question

I've been having some trouble with setting constraints on a UIImageView after initializing it with an image from the phone camera. If I run the code below:

UITextView *textView = self.textView;
UIImageView *imageView = [[UIImageView alloc] initWithImage:self.item.accessoryImage];
UILabel *label = self.textLabel;

self.accessoryImageView = imageView;
[self.contentView addSubview:self.accessoryImageView];

[self.contentView removeConstraints:self.contentView.constraints];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[textView]-2-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(textView, label)]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-100-[textView]-2-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(textView, label)]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[imageView(==100)]-10-[textView]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(imageView,textView)]];

auto layout decides to break the imageView(==100) constraint and instead sizes the imageView frame to be 2000+ points wide, which is the same size of the image. Does anyone know of a way around this situation?

Was it helpful?

Solution

Make sure the image view is not translating its autoresizing mask into constraints by calling [self.accessoryImageView setTranslatesAutoresizingMaskIntoConstraints:NO]. If that's set to YES, which it is by default, it will use the intrinsic content size (the size of the image) to generate size constraints. If you set it to NO, that doesn't happen.

OTHER TIPS

You are not being specific in this line:

[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[imageView(==100)]-10-[textView]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(imageView,textView)]];

I think you need to give format like this:

@"V:[imageView(==100)]-10-[textView]"

or

@"H:[imageView(==100)]-10-[textView]"

Autolayout needs to infer in which direction is that constraint needed. If you look at your console, it is probably complaining about missing layout (because it seems ambiguous).

Also what Scott answered is correct, you can tell your UIImageView to not to mess with the constraints.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top