I am using Auto layout and it\'s driving me crazy. I have done everything I could to prevent UIImageView from stretching all over. I have no idea why it does that. I tried u
You can try to add UIImageView programmatically.
Call this code in your viewDidLoad
method or where you want.
UIImageView *yourImageView = [[UIImageView alloc]initWithFrame:CGRectMake(50.0f, 50.0f, 320.0f, 320.0f)]; // x and y coordinates, width and height of UIImageView
[yourImageView setImage:[UIImage imageNamed:@"your_image.png"]];
[yourImageView setContentMode:UIViewContentModeCenter]; // you can try use another UIViewContentMode
[self.view addSubview:yourImageView];
My problem was with the ContentHuggingPriority
and ContentCompressionResistancePriority
.
The first controls how important it is to keep the view "hugging" the image (staying close to it and not expanding) and the latter controls how resistant to compression the view is.
We use PureLayout, so the code to fix it was:
[NSLayoutConstraint autoSetPriority:ALLayoutPriorityRequired forConstraints:^{
[myImageView autoSetContentCompressionResistancePriorityForAxis:ALAxisHorizontal];
[myImageView autoSetContentHuggingPriorityForAxis:ALAxisHorizontal];
}];
(my problem was only in the horizontal axis)
May 15, 2016: Updated to PureLayout v3 syntax. If you use a version <= 2 just put UIView
instead of NSLayoutConstraint
. Thanks Rudolf J!
With autolayout, the values in the Size Inspector are pretty much ignored.
You might expect that if a number is typed into the boxes on the Size Inspector, Xcode would automatically create constraints to reflect what you typed, but it doesn't. You need to create "Pin" constraints on your own for the height and width of your UIImageView
.
Select the image view on your storyboard
Click the "Pin" button at the bottom-right of the storyboard screen
Type the desired size into the "Width" and "Height" fields, and make sure the boxes are checked
Click the "Add 2 constraints" button
When you are done, you should be able to see your constraints in the Size Inspector on the right side of the screen (the purple boxes)
I had the same problem. I added a UIImageView into a prototype cell and wanted to align it next to the text but it kept stretching the image when I applied the constraints. In my case, I changed the 'Mode' property for the Image View to 'Aspect Fit' and it worked fine.
You'll want to make sure your UIImageView
is set to clip to bounds. If not, the image will spill out of the view and will appear to not stretch correctly (even though in reality it is).
In interface builder, make sure the Clip Subviews box is checked.
If you're not using interface builder, the following code will do the same thing:
yourImageView.clipsToBounds = YES;