Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize UIImageView after Scale Aspect Fit

I have a UITableViewCell containing only a UIImageView that is constrained to the superview on all four sides so that the cell scales to fit the full image.

The UIImageView is set to Scale Aspect Fit so that the large images resize to fit within the width of the cell. However, after the aspect fit takes place, the UIImageView remains the same size as before the scaling, and the cell in turn retains the size of the larger, unscaled image.

Is there any way in Interface Builder to force the height of the UIImageView to scale down when the image is scaled down by the Fit property? Or, equally, is there any way to programmatically tell the UIImageView to resize its height to match the newly scaled UIImage height?

like image 947
Dom Vinyard Avatar asked Oct 20 '22 07:10

Dom Vinyard


1 Answers

I encountered similar problem while embedding UIImageView into UIStackView. I consider this a bug because when image view has Mode:AspectFit then unbound dimension expected to resize to the scaled image instead of original.

My workaround was:

  1. created height constraint with identifier for the image view, e.g. "constraintImageHeight"
  2. in the code after putting a new image into the view, the constraint is reset to calculated height, e.g.:

    imgView.image = picture; for c in imgView.constraints { if c.identifier == "constraintImageHeight" { c.constant = picture.size.height * imgView.bounds.width / picture.size.width; break; } }

like image 183
Vladimir Avatar answered Oct 22 '22 02:10

Vladimir