I want to control the image alignment when using the UIViewContentModeScaleAspectFit
in UIImageView
.
For example, I have two UIImageView
in one view as above.these two UIImageView
's contentMode is UIViewContentModeScaleAspectFit
. Now I want to set image 3 to align right and image 4 to align left, so that these two images can be together.
I try to set the contentMode to UIViewContentModeScaleAspect|UIViewContentModeLeft
, but it make things worse.
Any suggestions are appreciated.
Rather than trying to left align the image within the image view, you could programatically add a width constraint to the image view so that there is no "excess space".
Suppose you have a
UIImageView
with "Aspect Fit" content mode, and a fixed height constraint added in the interface builder. Then, in the relevant view controller, check the aspect ratio of the image and apply the necessary width constraint to snap the image view to the contained image. E.g.:To apply this to your problem, you could constrain your two
UIImageView
s to be next to one another, set a fixed height constraint for both (of the same value), and then programatically set the width using the above code.Finally, I find UIImageViewAligned project which can work it out.
Thanks to @Marchy, there is also swift version UIImageViewAlignedSwift
Another option for some people might be to adjust the Content Hugging Priority on the
UIImageView
. In Interface Builder add a constraint to theUIImageView
with a low priority.This will satisfy the constraints until an image is added. Then set the UIImageView's Content Hugging Priority to a high value for width (or height if you are top/bottom aligning).
Then just set the UIImageView's Content Mode to what you want. Hope this helps!