'AutoLayout - Keep Ratio of Image With Horizontal Constraints (Swift Xcode 6)
I've been trying to implement a timeline of picture (as instagram or facebook). However, I've been struggling with the ratio of the image.
Here's my xib that contains my Cell :
I want the picture to keep its ratio and to completely fill the width of the cell. I've set 4 autolayout constraint on the UIImageView as 0-0 for horizontal constraint and 5-5 for top/bottom constraints. I've also set the ViewMode to "Aspect Fit".
I've tried different setup :
- set the height of UIImageView to a specific value : --> The width of the image is modify to keep the image ratio
- don't set the height of UIImageView --> it considers that the height is equal to 0 and therefore doesn't even display the image
- set the height greater or equal to a specific value : -- > same behavior as 1. (The width of the image is modify to keep the image ratio)
I'm loading the image from an URL so I've been using the lib Haneke (https://github.com/Haneke/HanekeSwift) with the following function : imageView.hnk_setImageFromURL(url).
It has an automatic resize of the image and I don't know how to get the original width/height of the image to set the height manually.
Again, what I want is the picture to keep its ratio and to completely fill the width of the cell.
Anyone has a suggestion ?
Thanks a lot !
Solution 1:[1]
This is the setup I came up with. It's a quick and dirty demo, but I would assume you'd want the image to always be centered. You can set the Horizontal and Vertical Center Constraint in storyboard to always keep it centered
If you want it to always completely fill the view, you can replace Equal Height
with Equal Width
, but by doing so, the imageView will run off the screen on some sizes because of the aspect ratio constraint
I've also included screenshots of the view at different sizes
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sean |