Reputation: 305
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.
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.
Upvotes: 3
Views: 1403
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
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