MirekE
MirekE

Reputation: 11555

Xcode autolayout: best fit for square

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:

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

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?

Upvotes: 2

Views: 278

Answers (2)

Er. Khatri
Er. Khatri

Reputation: 1414

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.

Upvotes: 0

Leonardo
Leonardo

Reputation: 1750

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

Upvotes: 2

Related Questions