Kyryl Nevedrov Kyryl Nevedrov - 1 year ago 95
Swift Question

How can I use UIImageView with aspectFill and alignment to the top?

How could I use

and alignment to the top? Auto-layout or programmatically don't mind.

dfd dfd
Answer Source

It can be done, but you are talking about quite a bit of coding. Let's start with a detailed description of what you are asking for.

We'll start with an iPhone6s in portrait mode with a screen size of 667x375 points, or a regular height by compressed width in size classes.

(Keep in mind, on any iPad you'll also need to work with slide-over and split screen too.)

But for now we'll go with 667x375. Into that we'll add our imageView as a square size of 375x375. Along the top of the screen when in portrait mode.

(Keep in mind that with AutoLayout you'll also have it pinned, and without putting some code in to determine if it's in landscape or portrait, otherwise, that 375x375 will shrink in landscape if you have other views underneath it.)

So now, stripped out to the most minimum (for now), we are talking about how to pin "an image" to the top of a UIImageView that is 375x375 in size and with a contentMode of aspectFill.

We need to find the size of the image next, based on both the largest dimension (height or width) AND how that dimension compares to the size of the imageView, calculate how the imageView will normally render it. The key figure you want is the height it will render it as

For instance, how will a 480x1020 (HxW) image fit into it? The 1020 width will be taken down to 375, so the height will be 480/(1020375) or 176.4705 points.

Always do the math for both dimensions - if your imageView isn't square or if the height isn't the "bounded" dimension, you'll be off.

Once you've calculated what the "Aspect Filled" height will be, check it against the dimensions of the imageView, and adjust the height of it as needed.

Here's where the real work comes in. If you are using AutoLayout, you can do a heightAnchor adjustment, but depending on how you pinned those other views things may be laid out really bad after you do. If you are using frames and CGRects be aware that you have to take into account iPad slide-out and split screen, etc.

Finally, if you want your app to load a different image in that imageView after it was loaded, you will have to "reset" the height back to what it originally was, at least in your calculations.

My recommendation is to find an alternative to what you are asking. For instance, put a small border around the image view to let the user know the true dimensions of that view.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download