Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 356
gemixin Avatar asked Feb 02 '26 12:02

gemixin


1 Answers

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

like image 126
André Slotta Avatar answered Feb 04 '26 05:02

André Slotta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!