Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine Auto Layout constraints with contentMode property of UIView

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?

like image 310
elitalon Avatar asked Sep 22 '13 17:09

elitalon


People also ask

What are two properties that auto Layout constraints control on a UIView?

Auto Layout defines margins for each view. These margins describe the preferred spacing between the edge of the view and its subviews. You can access the view's margins using either the layoutMargins or layoutMarginsGuide property. The layoutMargins property lets you get and set the margins as a UIEdgeInsets structure.

Does Uiimageview have intrinsic content size?

A vanilla UIView instance, for example, does not have an intrinsic content size. This means that you need to add four explicit constraints to describe the size and position of a UIView instance in a user interface.

How do I set constraints programmatically in Objective C?

NSLayoutConstraint *centreHorizontallyConstraint = [NSLayoutConstraint constraintWithItem:self. uiButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self. view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]; [self. view addConstraint:centreHorizontallyConstraint];


1 Answers

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.

like image 138
haik.ampardjian Avatar answered Oct 20 '22 01:10

haik.ampardjian