1
votes

I have a custom square view that can grow and shrink as needed. My custom view just overrides drawRect to render the content.

The containing view is a rectangle, but not a square. The aspect ratio changes depending on device orientation and type. I need to fit my custom view so that it takes maximum space in the container, but retains the 1:1 aspect ratio.

I would like to set the constraints in IB rather than code if possible. I have the following constraints:

  • Vertical centering in the container
  • Horizontal centering in the container
  • Aspect ratio (1:1)
  • Content mode set to scale to fill

I tried various things to make the custom view fit the container, which give me IB layout errors, for example:

  • Width <= container width
  • Height <= container height

I can't set any of the sizes equal, because I don't know if the container is vertical or horizontal...

This seems like a basic task, but I can't figure this out. What is the best way to fit square in a rectangle?

2

2 Answers

1
votes

Keep the constraints you already have, and add new constraints:

  • width and height equal to the superview, but with lower priorities than the aspect ratio constraint
  • width and height <= the superview size
0
votes

first three constraint are right., remove others and set the

  • leading or trailing and
  • top or bottom

constraint to superview

Now select the newely added constraint and make them >= (greater than or equal) to 0.

now you'll need to give the width or height constraint to your view which it can have it from its subview's same as we do it for scroll view or give a width equal to 320 to you view and make it also greater than or equal to.