user892028
user892028

Reputation: 305

ImageView with label that has a dynamic position 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.

Constraints

Upvotes: 3

Views: 1403

Answers (2)

André Slotta
André Slotta

Reputation: 14030

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() {
    super.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: https://www.dropbox.com/sh/oa8g96sknqqq97p/AADvEFpK2L9FbT-gBt5W49pQa?dl=0

Upvotes: 1

glm4
glm4

Reputation: 303

Can you show your constraint configuration? I think if you let the height free it will fit to the image you put on it.

Upvotes: 0

Related Questions