how to set the UIImageView align left or right when set the contentMode to UIViewContentModeScaleAspectFit?
Finally, I find UIImageViewAligned project which can work it out.
Thanks to @Marchy, there is also swift version UIImageViewAlignedSwift
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.:
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// UIImage loaded from somewhere...
imageView.image = uiImage
// Check the UIImageView for existing height constraints
let heightConstraints = imageView.constraints.filter{$0.firstAttribute == .height}
if let imageViewHeight = heightConstraints.first?.constant {
// Calculate the width which would make the image view fit
// the image perfectly, and constrain the view to that width.
let desiredImageViewWidth = (imageViewHeight / uiImage.size.height) * uiImage.size.width
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: desiredImageViewWidth))
}
}
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.
Another option for some people might be to adjust the Content Hugging Priority on the UIImageView
. In Interface Builder add a constraint to the UIImageView
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!