How to combine Auto Layout constraints with contentMode property of UIView
Asked Answered
P

2

14

I have a UIImageView object configured with Auto Layout. I have created constraints so that the view keeps a constant distance to its superview. In visual format it would be like:

@"V:|-[imageView]-|"
@"H:|-[imageView]-|"

But I would also like to keep the aspect ratio of the underlying image, so I have assigned UIViewContentModeScaleAspectFit to contentMode.

I thought everything was working well until I set the cornerRadius value of the associated CALayer:

self.imageView.layer.cornerRadius = 7;
self.imageView.layer.maskToBounds = YES;

Now when the image view is resized, e.g. due to a change in orientation, the rounded corners are lost depending on the new size the view gets. The reason is that cornerRadius applies to the UIImageView (frame in dashes below), but since the underlying image is also resized to respect contentMode (frame in asterisks below), rounded corners are not visible anymore:

--------------------------
|       **********       |
|       *        *       |
|       *        *       |
|       *        *       |
|       **********       |
--------------------------

Is there a way to prevent this behavior?

Pangenesis answered 22/9, 2013 at 17:21 Comment(0)
T
27

like @jacob-k said, you should add to your cell subclass layoutSubviews , but just to add you should call layoutIfNeeded first.

Example:

- (void)layoutSubviews
{
  [super layoutSubviews];
  [self layoutIfNeeded];
  imageView.layer.cornerRadius = imageView.frame.size.width / 2;
}

If you won't call layoutIfNeeded first, then it apply all changes without your set constraints.

Tarahtaran answered 23/5, 2014 at 20:27 Comment(4)
Thank you..working like a charm. struggling for so long.Willey
This work for a UITableViewCell only if you attach constraints to the tableview cell and NOT to the contentView. (views can still be added to the contentViewJanessa
this is the solution if you have complex constraints for all size classes in uitableviewcellHendley
How does anyone combine this approach with constraints animation that affects size of view?Jubilant
M
0

One quick way to do it could be to subclass UIImageView and set the corner radius in layoutSubviews.

Morgenthaler answered 26/11, 2013 at 16:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.