With Auto Layout, how do I make a UIImageView's size dynamic depending on the image?

Doug Smith picture Doug Smith · Nov 9, 2014 · Viewed 59.9k times · Source

I want my UIImageView to grow or shrink depending on the size of what the actual image it's displaying is. But I want it to stay vertically centered and 10pts from the leading edge of the superview.

However, if I set these two constraints it complains I haven't set up enough constraints to satisfy Auto Layout. To me it seems to perfectly describe what I want. What am I missing?

Answer

John Grant picture John Grant · Nov 10, 2014

The image view's intrinsic size is already dependent on the size of the image. Your assumptions (and constraints are correct).

However, if you've set up your image view in interface builder and have not provided it with an image, then the layout system (interface builder) won't know how big your image view is supposed to be at compile time. Your layout is ambiguous because your image view could be many sizes. This is what throws the errors.

Once you set your image view's image property, then the image view's intrinsic size is defined by the size of the image. If you're setting the view at runtime, then you can do exactly what Anna mentioned and provide interface builder with a "placeholder" intrinsic size in the property inspector of the image view. This tells interface builder, "use this size for now, I'll give you a real size later". The placeholder constraints are ignored at runtime.

Your other option is to assign the image to the image view in interface builder directly (but I assume your images are dynamic, so this won't work for you).