user892028 user892028 - 1 year ago 121
iOS Question

iOS Swift Autolayout ImageView with Label below for different sized images

I am trying to create a simple gallery image detail view in my iOS 9 Swift app.

I want the image at the top and the label underneath (for an image caption). However, all the images are different shapes and sizes.

I am using Aspect Fit for the image view which creates a problem for landscape images.

The image view does not resize to adjust the image so you end up with blank space above and below it, which creates a big gap between my image and caption.

In the examples below the yellow is the image view, the blue is the image itself with aspect fit resizing and the pink is the caption label.

Example Diagram

Any solutions for getting the imageview to aspect fit the image, but clip the image view accordingly to remove unused space? I tried ticking "Clip Subviews" in the storyboard to no avail.


Answer Source

i think the key is setting an aspect ratio constraint on the imageview.

class GalleryViewController: UIViewController {

  var image: UIImage!

  @IBOutlet weak var imageView: UIImageView!
  @IBOutlet weak var captionLabel: UILabel!

  override func viewDidLoad() {

    let aspectRatio = image.size.width / image.size.height
    imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: imageView, attribute: .Height, multiplier: aspectRatio, constant: 0.0))

    imageView.image = image
    captionLabel.text = (aspectRatio < 1.0) ? "Portrait" : "Landscape"

  @IBAction func viewWasTapped(sender: UITapGestureRecognizer) {
    presentingViewController?.dismissViewControllerAnimated(true, completion: nil)


take a look at my sample project:

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